Using the React.findDOMNode
method that was introduced in v0.13.0 I am able to get the DOM node of each child component that was passed into a parent by mapping over this.props.children
.
However, if some of the children happen to be React Elements rather than Components (e.g. one of the children is a <div>
created via JSX) React throws an invariant violation error.
Is there a way to get the correct DOM node of each child after mount regardless of what class the child is?
Access a DOM Element Using ReactDOM.findDOMNode() . findDOMNode() is used to find a specific node from the DOM tree and access its various properties, such as its inner HTML, child elements, type of element, etc.
In class-based components, the FindDOMNode() method is used to return DOM of the given element. Creating React Application And Installing Module: Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. foldername, move to it using the following command.
Firstly, let's pass data between a parent component and a child component. . First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function.
this.props.children
should either be a ReactElement or an array of ReactElement, but not components.
To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.
render() { return ( <div> {React.Children.map(this.props.children, (element, idx) => { return React.cloneElement(element, { ref: idx }); })} </div> ); }
You can then access the child components via this.refs[childIdx]
, and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx])
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With