Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

403
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda