Getting DOM node from React child element
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?
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 want to access any DOM element simply add ref
attribute and you can directly access that element.
<input type="text" ref="myinput">
And then you can directly:
componentDidMount: function()
{
this.refs.myinput.select();
},
Their is no need of using ReactDOM.findDOMNode()
, if you have added a ref
to any element.