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
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>
);
}
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
};
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)
}