Handling React Children

4 Minutes

charlie beemy profile picture
By
  • code
  • intermediate
  • react
React Logo pofo

This is aimed at authors of reusable libraries or individuals looking to create a reusable component. This pattern is not that common.

Have you ever wanted to access or modify the children for a wrapper React component? Well, you can! You might want to do this for 2 main reasons:

  1. Pass additional props or state stored in the wrapper component.

  2. Access any passed props in any of the child elements.

Why this might be useful

Let's take a real example that I implemented: Forms. Within a form, you'll have several input values that the user will submit. Some of these input values will be required, some optional, and some will depend on previous inputs to determine validity (think of confirm-password). Because the form validity is determined by each individual input element value, it makes sense to store all these values within a wrapper Form component. But in order to access these values (and at times modify these values), you will need to access the children's props within the Form component. If all the input child elements are valid, then the form should be able to submit. Otherwise, we can disable the submit button!

Now that we know how this pattern could be useful, let's look into how to implement it. We leverage React.Children() API to make this happen.

To get access to child props

To modify children's props

The above code works perfectly for components that expect all the same type of children, but what about when we have different kinds of children? What if we have custom components? Well, I coded a handy function that handles this! I call it validateChild:

Now combining everything together for a more complete solution

Made with