Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The getAttribute function is not always retrieving the attribute value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
    );
  }

enter image description here

>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>
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading