React: Pass value to method from onClick

/ Published in: JavaScript
Save to your folder(s)

How to pass a parameter into a method from an onClick method found in the render method.

Majority of the times when you need to do this, your adding it through a loop. In this case, call a function where the item in the loop will automatically be passed into the function. This will prevent the component from re-rendering every-time it's parent changes and none of it's props or state changed.

** DO NOT DO **
Adding the code below marked with DON'T DO, will cause this component to re-render every-time it's parent changes, regardless of whether this components state or props changed.

Copy this code and paste it in your HTML
  1. renderUser = user => {
  2. return <User key={} user={user} onClick={this.deleteUser} />;
  3. }
  5. render() {
  6. return (
  7. <div>
  8. <h1>Users</h1>
  9. <ul>
  10. {}
  11. </ul>
  12. </div>
  13. );
  14. }
  17. // DON'T DO
  18. return (
  19. <th value={column} onClick={() => this.handleSort(column)}>{column}</th>
  20. );

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.