Filter component children and display them conditionally?
Unanswered
Saltwater Crocodile posted this in #help-forum
Saltwater CrocodileOP
I have a component and I want to display some of the children inside a
Let's say I have something like this:
<Post>
<Post.Header/> (link)
<Post.Content/> (link)
<Post.Footer/> (div)
</Post>
Header, Content and Footer are all children of Post.
<Link> and others inside a simple <div>, based on a condition like the children name or something that gives me control over it. How could I do that?Let's say I have something like this:
<Post>
<Post.Header/> (link)
<Post.Content/> (link)
<Post.Footer/> (div)
</Post>
Header, Content and Footer are all children of Post.
1 Reply
Schneider’s Smooth-fronted Caiman
First you have to pass the children to the post as a prop
const Post = ({ children }) => { return ( <div> {React.Children.map(children, child => { if (child.type === Post.Header || child.type === Post.Content) { return <Link to="/some-path">{child}</Link>; } return <div>{child}</div>; })} </div> ); };
const Post = ({ children }) => { return ( <div> {React.Children.map(children, child => { if (child.type === Post.Header || child.type === Post.Content) { return <Link to="/some-path">{child}</Link>; } return <div>{child}</div>; })} </div> ); };