How to check if a React element will render anything

2.6k Views Asked by At

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?

2

There are 2 best solutions below

1
Joseph D. On

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>
3
Mohamed Ramrami On

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>
}