Victorqedu
Victorqedu

Reputation: 494

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.

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

Upvotes: 2

Views: 31

Answers (2)

abby
abby

Reputation: 65

The target property refers to the dom element on which the event originated so you have to use currentTarget just like this:

handleSearchChange(event) {
    const target = event.currentTarget;
    const name = target.getAttribute("name");
    console.log("Test name " + name + "\n");
}

if you would like to know more about difference between target and currentTarget see this here or here

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370789

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

Upvotes: 2

Related Questions