0

I was reading the docs Refs and the DOM and A complete guide to React refs to better understand the concept of refs in React. However, I am not sure why the concept is needed when it can be solved in the vanilla JS way.

For example, in the 2nd link mentioned above, the author of the article says that React does not provide an easy way to auto-focus a text element and that in such a scenario, refs would come in handy. To check that, I was experimenting with alternative methods to achieve the same auto-focus without refs. Here is a part of my solution:

class ExampleComponent extends Component {
  .
  .
  .
  componentDidMount () {
    // accessing an element without using refs
    const element = document.getElementById(this.inputId);

    if (element) {
      element.focus();
    }
  }
  .
  .
  .
  render () {
    return (
      <input id={this.inputId} onChange={this.handleChange} value={this.state.value} />
    );
  }
}

And it works.

How are refs better than the solution above? It seems pretty simple to me but I might be missing out on something.

Thanks in advance.

Black Wind
  • 193
  • 8
  • I realize that the above question does not cover the class component refs which is one of the 2 types of refs provided by React. If you have answers for that, great! If not, I'd be satisfied with the answer to the above HTML ref question alone – Black Wind Mar 19 '22 at 04:59

0 Answers0