Add onClick event to a group element (svg) with react

24,267

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;">
Share:
24,267

Related videos on Youtube

Clafouti
Author by

Clafouti

Frontend developer, UX lover, UI enthusiast.

Updated on July 09, 2022

Comments

  • Clafouti
    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
    Clafouti over 7 years
    Thanks 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
    Anthony Dugois over 7 years
    You 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
    NightOwl888 about 6 years
    The 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
    Shubham about 5 years
    I was just going through the svg docs. It seems that events can be added to <g> elements. Please refer here
  • Clafouti
    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
    Izhaki over 4 years
    I 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 the onClick handler is on one of its ancestors. This answer was the breakthrough.
  • stropitek
    stropitek almost 4 years
    pointer-events: bounding-box is not documented though developer.mozilla.org/en-US/docs/Web/CSS/pointer-events