A Small SVG Pitfall in React
When we want to use SVG image in React, we may import it like this:
import {ReactComponent as Logo} from "./logo.svg";
In my project, the logo.svg
is a X for user to click to delete the item in the list.
I added an onClick
function to it as below:
When we click on the X, the item
is undefined
. Hence, we can not delete it correctly. However, when we click on the space outside X, but within that square area, it can retrieve the item correctly from the data-item.
The crux of the issue is that we are using event.target
which is referencing the actual target that received the click. In this case, the <path>
tag. The data-item
is on<svg>
tag. Therefor, we cannot get the correct data.
It will only happen on SVG graphic as it is a vector graphic defined by a group of paths, boxes, circles, text etc. So, when we clicked on a SVG graphic, we may actually clicked on the paths, boxes, circles, text etc. but not the <svg>
itself.
Solution:
To solve it, we should use event.currentTarget
, which is always the object listening for the event. It always refers to the element to which the event handler has been attached(which is <svg>
tag in this case as we added the onClick
event handler to it).