I was trying to do this.
I must be missing something, but I don't understand why current
is always null
in this example.
class App extends React.PureComponent { constructor(props) { super(props); this.test = React.createRef(); } render() { return <div className="App">current value : {this.test.current + ""}</div>; } }
You can check my test case here
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. Copied!
This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM.
Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component. class MyComponent extends React. Component { constructor(props) { super(props); this.
useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.
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.
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