This is the test I made in a sandbox.
If you run the code and click the 2 buttons like this: first, back, first, back … a few times you will see at the console that the name attribute of the target event becomes null even if it was not null the first time I pressed that button.
I also attached an image with some comments in the lower right corner to clarify the behaviour.
This is the code:
handleSearchChange(event) {
const target = event.target;
const name = target.getAttribute("name");
console.log("Test name " + name + "\n");
}
render() {
return (
<div>
<div style={{ height: "30px", width: "30px" }}>
<FirstSVG name="first_page" onClick={this.handleSearchChange} />
</div>
<div style={{ height: "30px", width: "30px" }}>
<BackSVG name="back_page" onClick={this.handleSearchChange} />
</div>
</div>
);
}
>Solution :
The <svg> element will only be the target if it’s the innermost item clicked on. If you click on the <path> part of the SVG, for example, that’ll be the target instead.
While you could fix it by using event.currentTarget instead – which will reference the element the listener was attached to instead of the element the event was dispatched to – since this is React, a much better approach would be not to pass information through the DOM at all, and to instead convey it through JavaScript alone.
For example, you could have something like:
makeHandler(name) {
return () => {
console.log(name);
};
}
render() {
return (
<div>
<div style={{ height: "30px", width: "30px" }}>
<FirstSVG onClick={makeHandler("first_page")} />
</div>
<div style={{ height: "30px", width: "30px" }}>
<BackSVG onClick={makeHandler("back_page")} />
</div>
</div>
);
}
