Have you ever tried to access a React ref in the render()
method?
You might think the following would return the ref
:
class App extends React.Component {
myRef = React.createRef();
render() {
console.log(this.myRef);
return <div ref={this.myRef} />;
}
}
But it actually returns:
{
current: null;
}
So what gives?
Well if you think about it, a ref
is a reference to a DOM node. Hence, the ref
is only available when the DOM has rendered.
Most of the time, we’re using refs in events like onClick
handlers. In those cases, the DOM is already ready by the time the user interacts with the element.
The quickest way to access a ref is in componentDidMount
:
class App extends React.Component {
myRef = React.createRef();
componentDidMount() {
console.log(this.myRef);
}
render() {
return <div ref={this.myRef} />;
}
}
That’s because the lifecycle is invoked immediately after the component is mounted.
If you need to access the ref
in render()
, then you can use state:
class App extends React.Component {
myRef = React.createRef();
state = { isMounted: false };
componentDidMount() {
this.setState({ isMounted: true });
}
render() {
if (this.state.isMounted) {
console.log(this.myRef);
}
return <div ref={this.myRef} />;
}
}
You can check out this fiddle for an example: