Sometimes, we want to fix current is always null when using React.createRef with React.
In this article, we’ll look at how to fix current is always null when using React.createRef with React.
How to fix current is always null when using React.createRef with React?
To fix current is always null when using React.createRef with React, we assign the ref created by createRef
to an element.
For instance, we write
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
handleClick = () => console.log(this.test.current.value);
render() {
return (
<div>
<input ref={this.test} />
<button onClick={this.handleClick}>Get Value</button>
</div>
);
}
}
to create the test
ref with createRef
.
Then we assign test
as the value of the ref
prop of the input.
Finally, we get the ref’s value with this.test.current.value
, which should be set to the input.
Conclusion
To fix current is always null when using React.createRef with React, we assign the ref created by createRef
to an element.