Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

410
Vistas
Why should I use refs in React when I can perform the operation using getElementById?

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda