Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

current is always null when using React.createRef

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

like image 591
Sharcoux Avatar asked Aug 05 '18 09:08

Sharcoux


People also ask

Why is React ref current null?

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!

What does createRef return?

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.

What is React createRef ()?

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.

What is the difference between useRef and createRef?

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.


2 Answers

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.

like image 153
Mayank Shukla Avatar answered Oct 12 '22 03:10

Mayank Shukla


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.

like image 42
sktguha Avatar answered Oct 12 '22 04:10

sktguha