I have this code taken from the official React Ref docs
import React from "react";
import { render } from "react-dom";
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
// this.textInput.current.focus();
console.log(this.textInput);
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
const A = () => {
return <div>
<CustomTextInput />
</div>
}
render(<div><A/></div>, document.getElementById("root"));
and when the focusTextInput is called it logs "current: null". Here is the demo: https://codesandbox.io/s/wo6qjk9xk7
The code is fine since it's the exact same example present in react docs. Problem is your react-dom
version is older. React.createRef()
API was introduced in React 16.3 (all react
related packages should be 16.3+ in order to use React.createRef()
). Check this reference in docs.
Your dependencies:
"dependencies": {
"react": "16.6.3",
"react-dom": "16.2.0"
},
Problem fixed after updating react-dom
to 16.6.3
Check this: https://codesandbox.io/s/n7ozx9kr0p