The Startup
Published in

The Startup

A Small SVG Pitfall in React

Photo by Christopher Gower on Unsplash

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


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).




Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Why Is AngularJs the Right Choice for Your Next Mobile App?

Change Multiple Files Extension Using Single Line CMD

Async Concurrency in JavaScript

Upload files to GCP using multer , nodejs with visibility as public.

5 Use Cases for Array.from() in JavaScript

Let’s Build a Weather App

JavaScript Array Methods

JavaScript Weekly Issue 13

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Hi, I am interested in IT field including front-end, back-end, database, networking.

More from Medium

React Query: How to Memoize Results From useQueries Hook

React Class Components vs Function Components

React JS:18 Whats new about it?

How to Use Props in React