current is always null when using React.createRef

Sharcoux picture Sharcoux · Aug 5, 2018 · Viewed 49.4k times · Source

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

Answer

Mayank Shukla picture Mayank Shukla · Aug 5, 2018

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.