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
A React ref most commonly returns undefined or null when we try to access its current property before its corresponding DOM element is rendered. To get around this, access the ref in the useEffect hook or when an event is triggered.
The "Object is possibly null" error is caused because the useRef() hook can be passed an initial value as an argument and we're passing it null as an initial value. The hook returns a mutable ref object whose . current property is initialized to the passed argument.
useRef() only returns one item. It returns an Object called current . When we initialize useRef we set the initial value: useRef(0) . It's like doing this: const count = {current: 0} . We can access the count by using count.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With