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

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
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