Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting DOM node from React child element

Tags:

reactjs

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?

like image 749
Graham Conzett Avatar asked Apr 10 '15 18:04

Graham Conzett


People also ask

How do I get the DOM element from the React element?

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.

How do you find the DOM node in React?

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.

How do you get parent data from a child in React?

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.


1 Answers

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]).

like image 176
Alexandre Kirszenberg Avatar answered Nov 04 '22 07:11

Alexandre Kirszenberg