Accessing Children Components/Nodes
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 Parent
componentDidMount
lifecycle function.
The 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 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., <span>child2text</span>
). Thus, this.props.children
used in componentDidMount
lifecycle function for Parent2
component will be a direct reference to this React node (i.e., not an array containing a single reference).