Accessing Children Components/Nodes
If a component, when used, contains child React components or React nodes inside of the component (e.g.,
<Parent><Child /></Parent> or
<Parent><span>test<span></Parent>) these React node or component instances can be accessed by using
In the code below the
Parent component when used, contains two
<div> React node children, which contains React text nodes. All of the children instances, inside of the component are accessible using
this.props.children. In the code below I access these children inside of the
componentDidMount lifecycle function.
this.props.children of the
Parent component instance returns an array containing the references to the child React node instances. This array is logged out to the console. Additionally, in the
Parent component I am logging out the child of the first
<div> (i.e., a text node).
Note how when I use the
Parent2 component inside of the
Parent component the child React node of
Parent2 only contains one
<span> React node (i.e.,
this.props.children used in
componentDidMount lifecycle function for
Parent2 component will be a direct reference to this
<span> React node (i.e., not an array containing a single reference).
this.props.children can potentially contain a wide set of nodes and components React provides a set of utilities to deal with this data structure. These utilities are listed below.
Invoke fn on every immediate child contained within children with this set to thisArg. If children is a keyed fragment or array it will be traversed: fn will never be passed the container objects. If children is null or undefined returns null or undefined rather than an array.
Like React.Children.map() but does not return an array.
Return the total number of components in children, equal to the number of times that a callback passed to map or forEach would be invoked.
Return the only child in children. Throws otherwise.
Return the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
- When there is only a single child,
this.props.childrenwill be the single child component itself without the array wrapper. This saves an array allocation.
- It can be confusing at first to realize that
childrenare not what a component returns, but instead what is contained inside of component anywhere (including in a
render) it is instantiated.