Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: wrap child component in div if it does not return null

Tags:

reactjs

Using React, how can a child component be wrapped conditionally in another element if it is not returning null when rendered?

export const Parent = ({children}) => (
  <div className="row">
    {React.Children.map(children, child =>
      <div className="col-6 col-s-4 col-md-3">
        {child}
      </div>
    )}
  </div>
);

This might be related to the discussions in React component children detect if empty / null before render however, none of the proposed approached seemed to work (ReactDOMServer.renderToStaticMarkup seem to have issues with SSR and React.isValidElement is persistently treating the component that returns null as a valid element). I've got a feeling that this is sort of an anti-pattern, as it seems to be real hard to do. Only solution I can think of at the moment is moving the column div into the child component and clone a prop into the child to inform it that a wrapping column div is desired... Which seems way hacky.

like image 966
user42488 Avatar asked Sep 02 '25 15:09

user42488


1 Answers

If you don't want to use

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

try with:

const isChildNull = children => {
  return Boolean(children.type() === null); //--> will return the tag type
};

If child component receives props, don't forget to pass those props when calling type function:

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

EDIT: working example here: https://stackblitz.com/edit/react-a29daw

like image 98
lissettdm Avatar answered Sep 05 '25 04:09

lissettdm