Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS children - filter out null values

Tags:

reactjs

I'm rendering my components with:

<PanelGroup>
    {this.renderPanel1()}
    {this.renderPanel2()}
    {this.renderPanel3()}
</PanelGroup>

Now one of my panels is only available if its available-property is set to true. The render()-method otherwise returns null.

My <PanelGroup> should add a divider on the bottom of all elements except in the last element.

I tried to accomplish that with the following code, but because even if panel2 is returning null, the divider is still added, and the code won't work.

How can I filter out all my panels which are returning null? :)

<div>
   {React.Children.map(
       React.Children.toArray(props.children),
           (child: React.ReactElement<PanelProps>, i) => {
               return (
                     <div>
                        {React.cloneElement(child as React.ReactElement<PanelProps>, child.props)}
                        {/*Add divider after all elements except last*/}
                        {i < React.Children.count(props.children) -1 && <Divider/>}
                     </div>
                )
           }
        )}
</div>
like image 613
sleepysimon Avatar asked Sep 13 '18 14:09

sleepysimon


People also ask

How do you filter kids React?

If you want to filter the children, you could use React. Children. toArray to obtain a normal JS array and then use its Array. prototype.

How remove null from Array in React?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.

How do you check if a React is null?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run.

How do I know if my React component renders null?

No, there's no way to determine what a child will render using React. The standard way to do this is to expose some utility function that says whether A will render. Save this answer.


1 Answers

You have to take advantage of Array.filter():

const MyComponent = ({ children }) => {
  // This filter will return only not null values
  const children = React.Children.toArray(children).filter(Boolean);
  
  // return ...
};

Working example:

const array = [1,2,3,null,4,null,5,null];
console.log(array.filter(Boolean));
like image 64
Mosè Raguzzini Avatar answered Sep 29 '22 10:09

Mosè Raguzzini