Reputation: 135
I was playing with React.Children
and children
property and i found that there is no difference between using children.filter()
and using React.Children.toArray(children).filter
i was also able to render a specific child from the children props by using it's index directly and treat it like a normal array
so i wonder is there any difference between the two approaches? and if i can use the props directly with the arrays method why the react team implemented the toString()
method in the first place
i tried console.log() the two of them and i see no defference between the two approaches
const ChildrenContainer = (props) => {
const { children, howMany } = props;
console.log(children, '\n', Children.toArray(children));
return (
<div className="card-columns">
{Children.map(children, (thisArg) => thisArg)}
</div>
);
}
Upvotes: 4
Views: 944
Reputation: 33161
If you look at the docs here: https://reactjs.org/docs/react-api.html#reactchildren you will notice some things.
React.Children
deals with null
and undefined
. Calling children.filter()
would error should children be null or undefined.
It deals with <Fragment>
children
Includes helper functions such as .only()
that provide more react specific capabilities than a regular array.
toArray()
alters keys to preserve semantics of nested arrays.
So in your specific case, you might not notice any difference. But even if you are certain that children
will always be a usable array, it is still good practice to use React.children
. This is because it abstracts away the children concept so that your code is more future proofed (for changes to your code, and potential changes to react itself).
Upvotes: 5