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>
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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With