How to filter out null children values with React?

Sometimes, we want to filter out null children values with React.

In this article, we’ll look at how to filter out null children values with React.

How to filter out null children values with React?

To filter out null children values with React, we can use the React.Children.toArray method to convert the children prop to an array.

Then we can use the array’s filter method to filter out the null values.

For instance, we write:

import React from "react";

const MyComponent = ({ children }) => {
  const c = React.Children.toArray(children).filter(Boolean);

  return <div>{c}</div>;
};

export default function App() {
  return (
    <div>
      <MyComponent>
        <p>foo</p> {null} <p>bar</p>
      </MyComponent>
    </div>
  );
}

to define the MyComponent component that takes the children prop.

And in it, we call React.Children.toArray with children to convert the children prop object to an array.

Then we call filter to return a new array without the null values.

Finally, in App, we add the items in between the MyComponent tags.

And we can see that only the p elements are rendered.

Conclusion

To filter out null children values with React, we can use the React.Children.toArray method to convert the children prop to an array.

Then we can use the array’s filter method to filter out the null values.