React & SVG: How do I make <path> support onClick? React & SVG: How do I make <path> support onClick? reactjs reactjs

React & SVG: How do I make <path> support onClick?


This worked for me.

svg {    pointer-events: none;}path{    pointer-events: auto;}

Then we can add on click event on path. worked!! thanks


I wrap my SVG with a div and apply any attributes that I desire (click handlers, fill colors, classes, width, etc..), like so (fiddle link):

import React, { PropTypes } from 'react'function XMark({ width, height, fill, onClick }) {    return (        <div className="xmark-container" onClick={onClick}>            <svg className='xmark' viewBox="67 8 8 8" width={width} height={height} version="1.1" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink">                <polygon stroke="none" fill={fill} fillRule="evenodd" points="74.0856176 9.4287633 71.5143809 12 74.0856176 14.5712367 73.5712367 15.0856176 71 12.5143809 68.4287633 15.0856176 67.9143824 14.5712367 70.4856191 12 67.9143824 9.4287633 68.4287633 8.91438245 71 11.4856191 73.5712367 8.91438245 74.0856176 9.4287633 74.0856176 9.4287633 74.0856176 9.4287633" />            </svg>        </div>    )}XMark.propTypes = {    width: PropTypes.number,    height: PropTypes.number,    fill: PropTypes.string,    onClick: PropTypes.func,}XMark.defaultProps = {    width: 8,    height: 8,    fill: '#979797',    onClick: null,}export default XMark

You can of course ditch the wrapper and apply the onClick to the svg element as well, but I've found this approach works well for me!(I also try and use pure functions when possible https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc)


I did it this way:

Just using polyline for example, it could be any SVG element.

export default class Polyline extends React.Component {    componentDidMount() {        this.polyline.addEventListener('click', this.props.onClick);    }    componentWillUnmount(){        this.polyline.removeEventListener('click', this.props.onClick);    }    render() {        const {points, style, markerEnd} = this.props;        return <polyline points={points}                     ref={ref => this.polyline = ref}                     style={style}                     markerEnd={markerEnd}/>;    }}
  • get ref in ref callback
  • on componentDidMount add click event listener to the ref
  • remove event listener in componentWillUnmount