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

122
Visualizações
Get dataset of parent, while clicking on child

I have the following code, in which I have a button with data attribute and div inside of it, I want to get the dataset of button, no matter how deep is the target inside of a child.

export default function App() {
  const handler = (e) => {
    console.log(e.target.dataset.id);
  };
  return (
    <div className="App">
      <button
        data-id="myDataId"
        onClick={handler}
        style={{ 
          height: 200, 
          width: 200, 
          backgroundColor: "green" 
        }}
      >
        Bruh
        <div
          style={{
            height: 100,
            width: 100,
            backgroundColor: "red"
          }}
        />
      </button>
    </div>
  );
}

In this example, my console gives undefined when I click inside of the div, but if Iclick to button, it gives my data attribute.

I tried to use event.path, but it didn't give any results.

Is there any generic way to get the dataset of my button?.

Here is the fully working example: https://codesandbox.io/s/lucid-breeze-e1lh2?file=/src/App.js:23-535

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

0

import "./styles.css";
import {useRef} from 'react'
export default function App() {
  const myContainer = useRef(null);
  const handler = (myContainer) => {
    console.log(myContainer.current.closest(".parent").getAttribute("data-id"))
  };

  return (
    <div className="App">
      <button
        data-id="aaaaaaa"
        className = "parent"
        onClick={() => handler(myContainer)}
        style={{ height: 200, width: 200, backgroundColor: "green" }}
      >
        Bruh
        <div
        ref={myContainer}
          style={{
            height: 100,
            width: 100,
            backgroundColor: "red"
          }}
        />
      </button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The problem was that I should've gotten the dataset from the currentTarget not from the target.

The difference is that the target comes from the exact element on which was performed click, and the currentTarget is the element on which onClick was set.

const handler = (e) => {
  console.log(e.currentTarget.dataset.id); // instead of e.target
};
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the parentElement property of the target.

If you don't know how deep the target might be, you can loop through ancestors until you find it. There is an example:

const handler = (e) => {
  let target = e.target
  while (target && target.tagName != 'BUTTON') target = target.parentElement

  console.log(target?.dataset.id)
}
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