Add onClick event to a group element (svg) with react
Solution 1
A g
element is just an empty container; it can not fire events by itself.
If you run this example, you'll see that you can trigger the click
event by clicking on the children of the g
element, but you can't if you click in the empty space between them.
You have to use actual shapes to fire events in SVG.
Solution 2
Use style pointer-events as bounding-box to make the group clickable any where on the group.Even at the empty places
<g id="Group" onClick={this.clickGroup.bind(this, 1)} style="pointer-events: bounding-box;">
Related videos on Youtube
Comments
-
Clafouti almost 2 years
I'm trying to add an onClick event to an existing svg. Right now I have this :
<g id="Group" onClick={this.clickGroup.bind(this, 1)}>
Which somewhat works but not entirely... The event fires when I click the group but the "zone" that is clickable isn't the same as the group I want to be clickable (it seems completely random to me).
Is there any better way to add events to a
<g>
element (with React ?) ? -
Clafouti over 7 yearsThanks for your help. Does that mean that the best solution would be to wrap all the paths that form a shape inside something like a rectangle ?
-
Anthony Dugois over 7 yearsYou can add a transparent rectangle on top of your shapes and attach an event on it. If someone has a more elegant solution, would be glad to see it.
-
NightOwl888 about 6 yearsThe answer box is only for complete answers to the question. This feels like it would be better suited as a comment. Changing the text so that it directly addresses the question that was asked improves the long-term value of the answer and helps to prevent it from being deleted during review.
-
Shubham about 5 yearsI was just going through the svg docs. It seems that events can be added to <g> elements. Please refer here
-
Clafouti about 5 years@Shubham Indeed you can. But as @anthony-dugois said,
<g>
is an empty container, so if you do not populate that container with other elements, you won't be able to fire events from it. -
Izhaki over 4 yearsI dread this answer being a comment. I have just spent two hours trying to figure out how have a
g
element the actual target when theonClick
handler is on one of its ancestors. This answer was the breakthrough. -
stropitek almost 4 years
pointer-events: bounding-box
is not documented though developer.mozilla.org/en-US/docs/Web/CSS/pointer-events