Reputation: 3521
I have something like a card which i want it to be clickable. The problem here is I have a data attribute that I need the value on the click event. Therefore when I click the image obviously it will get me undefined because the wrong element triggered the click event. So I added pointer-events: none
to the image and it worked but even have to add it to the figcaption
because this will also have the same behaviour.
function App () {
return (
<figure
onClick={(e)=>console.log(e.target.getAttribute("data-mode"))}
data-mode="some-data-mode"
className="game-mode-figure"
>
<img
style={{pointerEvents: "none"}}
className="img-fluid"
src="https://via.placeholder.com/60x60"
alt="English 4 Fun"
/>
<figcaption>Sample Title</figcaption>
</figure>
)
}
ReactDOM.render(<App/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
So my question is basically, without having to set pointer-event none in everything, how can I make the Figure element be the only one to capture the click event ? As in, I click the image or where the figcaption is and it will behave like I clicked the figure element and I can access the data attribute.
Upvotes: 1
Views: 780
Reputation: 14191
An alternative to your proposed requirement is to traverse to the closest element with the said data attribute - no need for pointer-events: none
if you do this
onClick={(e) => {
// of course you would only need to traverse if child is clicked
// you can write additional logic for that checking
let data_mode = e.target.closest("figure").getAttribute("data-mode");
}}
But to be answer complete, you can simplify your CSS like this:
figure * {
pointer-events: none;
}
Upvotes: 3