Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a React element will render anything

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?

like image 535
Tamlyn Avatar asked Sep 30 '19 10:09

Tamlyn


Video Answer


2 Answers

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>
}
like image 188
Mohamed Ramrami Avatar answered Oct 20 '22 00:10

Mohamed Ramrami


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>
like image 29
Joseph D. Avatar answered Oct 19 '22 23:10

Joseph D.