Say I'm making a wrapper component which should only render itself if some child nodes are passed in:
const Wrapper = ({children}) => {
if (!children) return null
return <div>{children}</div>
}
The problem is that children
could be a Fragment
containing null, or an array of nulls. Or a fragment containing a fragment containing...
<Wrapper>hey</Wrapper> // renders <div>hey</div> π
<Wrapper>{null}</Wrapper> // renders nothing π
<Wrapper>{[null]}</Wrapper> // renders <div/> π
<Wrapper><React.Fragment>{null}</React.Fragment></Wrapper> // renders <div/> π
Is there a canonical way to check for all these conditions?
Maybe this is what you're looking for :
import ReactDOMServer from 'react-dom/server';
const Wrapper = ({children}) => {
const markup = ReactDOMServer.renderToStaticMarkup(children);
if (!markup.trim()) return null;
return <div>{children}</div>
}
No need to check. They simply don't render.
false, null, undefined, and true are valid children. They simply donβt render. These JSX expressions will all render to the same thing:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With