I'm trying to add an event listener to a SVG path in a React component. I followed a previous Stack Overflow answer (How to access SVG elements with Javascript) that used an anonymous function, and that worked fine. When I tried to set the callback to a function defined inside the React component class, as in this Stack Overflow answer (ReactJS - Add custom event listener to component), the function is not called. Interestingly, if I make a reference to the function in the componentWillMount and use the reference, it works.
import React, { Component } from "react";
export default class ProcessMap extends Component {
constructor(props) {
super(props);
this.hover = this.hover.bind(this);
}
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
svg.addEventListener("load", function() {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
//path1.addEventListener("click", this.hover, false); // this did not work
path1.addEventListener("click", t, false); // this works
});
}
hover() {
console.log("hover");
}
render() {
return (
<div>
<object id="drawing-svg" width="300" height="400" type="image/svg+xml" data="images/drawing.svg"></object>
</div>
);
}
};