current is always null when using React.createRef
Because you forgot to assign the ref to some dom element. You are only creating it.
Write it like this:
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
handleClick = () => alert(this.test.current.value)
render() {
return (
<div className="App">
<input ref={this.test} />
<button onClick={this.handleClick}>Get Value</button>
</div>
)
}
}
Working Example.
I know this is not the solution to OP's problem but for those who are coming from google search, one of the ways the ref.current can be null is that if the component on which the ref is being attached is a connected component. Like with react-redux connect or withRouter. For react-redux the solution is to pass forwardRef:true in the fourth option to connect.
React.createRef() is asynchronous so if you try to access the ref in componentDidMount, it will return null and later return the properties of the component in which you are referencing.
componentDidMount(): void {
if (this.viewShot && this.viewShot.current) {
this.viewShot.current.capture().then((uri) => {
console.log('do something with ', uri);
});
}
}
This is the right way to use the React.createRef() in this context.
You're missing the ref={this.test}
prop.
return (
<div className="App" ref={this.test}>
current value : {this.test.current + ""}
</div>
);