Search code examples
javascriptreactjsref

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


Solution

  • 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.