Making the most out of the children in React components.
Children (props.children) according to React Documentation is an ‘opaque’ data structure. All that means is don’t mess with them directly. Luckily React offers some utilities to work with Children easier.
The basic structure of a React Child, that is a looks something like this:
A React Child has a few key properties that you might want to work with:
Q: Do all children look like this?
A: No. Children can be strings, booleans, numbers, null, etc. You can verify it is a valid react element by using React.isValidElement(object). This checks that the variable passed to it is an object, and it has the correct symbol for $$typeof.
React offers a few utilities to work with children. You can read more about them here: React Children Documentation.
First up is the map utility. This is very similar to Array.protoype.map, but it has 1 key difference. If children is null or undefined it will return null and not an array. This is useful since react will not render and array or undefined. This is extremely useful if you want to pass extra props to this children:
The forEach utility behaves the same as the map utility, but it does not have a return value, similar to Array.prototype.forEach. This can be used to filter out children or find a certain child the component needs to work with.
This one is self explanatory. It returns the count of the children.
The only utility will return the only child in children, and if there is more than one is will throw. This is very useful to limit the amount of immediate children that can be passed to a component.
Another pretty self explanatory utility. toArray converts the children object to an array. It also assigns a key to each child to scope them to the input array. This is useful if you need to reorder or slice the children object.
One thing that has come up in articles about Vue vs React is the lack of “slots” in React. While this could easily be done by just passing the “slots” down as props, slots with a similar API to shadow DOM or Vue can also be implemented using React’s Children utilities.
Note: It is probably more efficient to do this with props, since we will need to traverse over the Children any component that is passed a decent amount of root level children could cause performance hits.
The above example is a quick example of how you could use the Children utilities. For a more in depth example you can checkout react-slotted.
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!