React component children detect if empty / null before render

Solution 1:

Get the children type. It will return null if Child component returns null:

const isChildNull = children => {
  return Boolean(children.type()=== null);
};

Solution 2:

Using ReactDOMServer.renderToStaticMarkup. It converts the jsx elements to string. If children returns null then renderToStaticMarkup will return an empty string:

import ReactDOMServer from 'react-dom/server';

const isChildNull = children => {
  return !Boolean(ReactDOMServer.renderToStaticMarkup(children));
};

Usage:

const Child = () => {
  return null;
};
    
const Parent = ({ children }) => {
  const isNull = isChildNull(children);
  if (isNull) {
     return "render null";
  }
  return <div>{children}</div>;
};
    
export default function App() {
   return (
     <Parent>
        <Child />
     </Parent>
   );
}

Working example using solution 1

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)