2

I was curious how one may be able to access data within a map function so that it can be used within the event parameter when passing down a function within an onClick function in React.

Here is my handleClick function. I would like to gain access to the "d" named property from the map function using the event in handleClick If there's another way to gain access to the variable "d" so that I could use it in handleClick that would be really great. I couldn't find a specific solution for this type of scenario so I was wondering if I could get some help. Thanks!

// Gain access to the parameter data from the map function  
public handleClick(event: React.MouseEvent<HTMLAnchorElement>) {
    console.log(event);
  }
  public render() {
    return (
      <div className="">
        {this.props.data.slice(0, MAX_RESULTS_LENGTH).map((d: any) => (
          <a tabIndex={0} onClick={this.handleClick} key={d.id}>
            {d.address}
          </a>
        ))}
      </div>
    );
  }
}

1 Answer 1

3

Just pass it as an inline function

  public render() {
    return (
      <div className="">
        {this.props.data.slice(0, MAX_RESULTS_LENGTH).map((d: any) => (
          <a tabIndex={0} onClick={e => this.handleClick(e, d)} key={d.id}>
            {d.address}
          </a>
        ))}
      </div>
    );
  }
}

public handleClick(event: React.MouseEvent<HTMLAnchorElement>, d: any) {
    console.log(event, d);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a more efficient way of doing this? Aren't inline functions more inefficient. I get an error involving rendering performance in jsx
Not at all. You could encapsulate it in a regular function. But there will be no performance gain whatsoever
More efficient way would be to use bind this.handleClick.bind(this, d) The this part doesn't matter if it's already bound (or doesn't have to be), but it lets you choose what parameters will be sent when the function is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.