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

119
Visualizações
Quick way to reference an element in a React component?

I have a component that has an input field and button. I want to add an onclick handler on the button that uses the value of the input. I can do this with querySelector, or getElementbyId or having a parent form element, or changing the input to a component. But what I want to know is if there's a direct and easy way just to refence the element.

import React from "react";

export default class UserInput extends React.Component{
  constructor(props){
    super(props);
    this.doStuff = this.doStuff.bind(this);
  }

  doStuff(){
    const inputValue = document.getElementById('new-task').value // I want to replace this
    // do stuff
  }

  render(){
    return(
      <div id="user-input">
        <input type="text" id="new-task"></input>
        <button type="button" onClick={this.doStuff}>Do Stuff!</button>
      </div>
    )
  }
}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

I think you can do it this way. Just give it a try.

import React from "react";
export default class UserInput extends React.Component{
  constructor(props){
    super(props);
    this.textInput = React.createRef();
    this.doStuff = this.doStuff.bind(this);
  }

  doStuff(){
    const inputValue = this.textInput
  }

  render(){
    return(
      <div id="user-input">
        <input type="text" id="new-task"  ref={this.textInput}></input>
        <button type="button" onClick={this.doStuff}>Do Stuff!</button>
      </div>
    )
  }
}
about 4 years ago · Santiago Gelvez Relatório
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