3

I don't if this is a "Reacty" solution but I need to get parent component's class name from child component and here is why. If you can provide a different approach to this solution, I would be greatful.

I have the following components:

  • ArticleHeader
  • ArticleMeta
  • ArticleBody
  • ArticleImage
  • Article

The Article component currently includes all the other components but I want to change that. I want my Article component to be like this:

 render() {
     return (
          <article className={this.props.className}>
              {this.props.children}
          </article>
     );
 }

And I want someone to write something like:

 <Article className="news-single">
      <ArticleImage image="someimage.jpg" />
      <ArticleHeader title="Test" />
      <ArticleBody> <p>loren ipsum</p> </ArticleBody>
 </Article>

I want ArticleImage, ArticleHeader, and ArticleBody to inherit className of parent so I can have classnames such as:

 .news-single
 .news-single-header
 .news-single-image
 .news-single-body

How can I get the parent component's className from child component?

Gasim
  • 7,615
  • 14
  • 64
  • 131
  • 2
    Why not do a simple .new-single > .header, .new-single > .image on your css to make it work. Or else pass the classname as props – Semi-Friends Nov 07 '16 at 21:15
  • @Semi-Friends I don't do CSS nesting. Passing the classname as props is my last resort because to me both these components are tied to each other, so I want a solution that automates this task as much as possible. – Gasim Nov 07 '16 at 21:19
  • @azium Have you done this solution? Does it have performance implications because of cloning the component? – Gasim Nov 07 '16 at 21:20
  • Okay. I think the one that azumi commented is what you need – Semi-Friends Nov 07 '16 at 21:22
  • 1
    This is common practice, no performance penalty. This is the standard way of passing props to `children` – azium Nov 07 '16 at 21:27
  • this question is already answerd :) https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children – Rizwan Feb 06 '19 at 12:38
  • You could use react context as well. The example they provide in the documentation is to style components as well. https://reactjs.org/docs/context.html#when-to-use-context – José Salgado Feb 18 '19 at 18:07

1 Answers1

0

A more "Reacty" way of doing this would be to just use CSS classes and inheritance. Set an appropriate class (.header, .body) on your child component, and use a descendant selector to style it. So you would have:

 .news-single
 .news-single > .header
 .news-single > .image
 .news-single > .body

This way you can also apply a common style to all .headers on the page, for example.

Scimonster
  • 32,893
  • 9
  • 77
  • 89