Reputation: 53853
In the following example this.refs.foo.clientWidth
returns undefined
and I can't figure out why. How can I get the reference to SomeComp
in PageComp
to use its width? (using React 15.2.1 or similar)
class PageComp extends React.Component {
componentDidMount() {
console.log(this.refs.foo.clientWidth);
}
render() {
return (
<div>
<p>{this.props.name}</p>
<SomeComp ref="foo" />
</div>
);
}
}
class SomeComp extends React.Component {
render() {
return (
<div>
<h1>I loaded</h1>
</div>
);
}
}
ReactDOM.render(
<PageComp name="Joe Schmoe"/>,
document.getElementById('react_example')
);
Upvotes: 3
Views: 2603
Reputation: 3375
this.refs.foo
returns React Element.
But if you want to work with DOM element - you need to find this Node
React 15.0.1 Requires this syntax: ReactDOM.findDOMNode(this.refs.foo)
JSBIN: http://jsbin.com/xabidaquti/1/edit?html,js,console,output
Upvotes: 5
Reputation: 664
For better clarity, this.refs.foo.clientWidth
will work if the refs
is set to html elements like div
, input
and so on. As refs
by itself will return the DOM Node in case of such html elements.
If the refs
is set to some React components, then we can access the DOM Node of the Components only using ReactDom.findDOMNode(this.refs.foo)
and hence we need to get the clientWidth
using ReactDom.findDOMNode(this.refs.foo).clientWidth
.
Upvotes: 0
Reputation: 718
Try like this ReactDOM.findDOMNode(this.refs["foo"].clientWidth)
Upvotes: 0