Deprecation warning using this.refs

The Lint rule you are referring to is called no-string-refs and warns you with:

"Using string literals in ref attributes is deprecated (react/no-string-refs)"

You are getting this warning because have implemented the deprecated way of using refs (by using strings). Depending on your React version, you can do:

React 16.3 and later

constructor() {
  super();
  this.btnRef= React.createRef();
  this.state = { clicked: false };
  this.handleClick = this.handleClick.bind(this);
}

render() {
  return (
    <div>
      <div onClick={this.addVote}><span ref={this.btnRef} className="glyphicon">&nbsp;</span></div>
    </div>
  );
}

React 16.2 and older

constructor() {
  super();
  this.btnRef;  //not necessary to declare the variable here, but I like to make it more visible.
  this.state = { clicked: false };
  this.handleClick = this.handleClick.bind(this);
}

render() {
  return (
    <div>
      <div onClick={this.addVote}><span ref={(el) => this.btnRef = el} className="glyphicon">&nbsp;</span></div>
    </div>
  );
}

For even better readability, you could also do:

render() {
  let myRef = (el) => this.btnRef = el;
  return (
    <div>
      <div onClick={this.addVote}><span ref={myRef} className="glyphicon">&nbsp;</span></div>
    </div>
  );
}

Have a look at what the official documentation says on Refs and the DOM, and this section in particular:

Legacy API: String Refs

If you worked with React before, you might be
familiar with an older API where the ref attribute is a string, like
"textInput", and the DOM node is accessed as this.refs.textInput. We
advise against it because string refs have some issues, are considered
legacy, and are likely to be removed in one of the future releases. If
you’re currently using this.refs.textInput to access refs, we
recommend the callback pattern instead.

Leave a Comment