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

151
Visualizações
How to I access DOM element using 'this' keyword in React

In vanilla Javascript I can access 'this' keyword in event listeners like this:

  <body>
    <button type="button" onclick="test(this)">Click Me</button>
    <script>
      function test(t) {
        console.log(t); //this 
      }
    </script>
  </body>

or like this

  <body>
    <button id="test" type="button">Click Me</button>
    <script>
      document.getElementById("test").onclick = function () {
        console.log(this);
      };
    </script>
  </body>

But how do i access DOM element using 'this' keyword in react event listener

export default function Button() {
  function test() {
    console.log(this); //undefined
  }
  return (
    <button onClick={test} id="test" type="button">
      Click Me
    </button>
  );
}

I know I can access the target element using 'event' object. But I'm curious whether it is possible to use 'this' in react event listener

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Pass a parameter to get the event argument.

e.g:

function test(event) {
    console.log(event.target); // returns the element which trigered the event
    console.log(event.currentTarget); // returns the element that the event listener is attached to.
 }

But if you want to don't want to do it this way, you can use the querySelector method inside the event too.

   const element = document.querySelector("#test");
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use ref to access DOM nodes in React.

import React, { useRef } from "react";

function Button() {
  const buttonRef = useRef(null);
  function test() {
    console.log(buttonRef.current); 
  }
  return (
    <button onClick={test} id="test" type="button" ref={buttonRef}>
      Click Me
    </button>
  );
}

Read more about ref here: https://reactjs.org/docs/hooks-reference.html#useref

about 4 years ago · Juan Pablo Isaza 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