What is the right of getting the react ref value on an event in a class Component?

class ReactRef extends Component {
  constructor(props) {
    super(props);
    this.buttonValue = React.createRef();
  }


  hasText() {
    console.log(this.buttonValue.current); //Cannot read property 'buttonValue' of undefined
  }


  render(){
   return(
     <div>
      <button type="text" ref={this.buttonValue} onClick={this.hasText}> Click me </button>
     </div>
    )
   }

 }

1 Answers

2
larz On Best Solutions

You need to bind hasText to the correct scope.

You can either declare it with an arrow function -

hasText = () => {
  // now you have access to this.buttonValue.current
}

Or you can bind it inside your constructor -

constructor(props) {
  super(props);
  this.buttonValue = React.createRef();
  this.hasText = this.hasText.bind(this);
}