Home >Web Front-end >JS Tutorial >How to Pass Values to onClick Events in React?

How to Pass Values to onClick Events in React?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 00:48:10453browse

How to Pass Values to onClick Events in React?

Passing Values to onClick Events in React

React's onClick event handler does not natively accept parameters. When onClick is triggered, it displays synthetic event properties devoid of any explicit value transfer. To overcome this, several approaches can be employed:

Arrow Function (Easy Way)

An arrow function can be used to manually pass values to the onClick handler:

return (
  <th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);

This creates a new function that invokes handleSort with the desired parameters. However, excessive function creation can lead to unnecessary re-renders.

Sub-Component (Optimal Method)

Extracting the handler into a sub-component enhances performance by preventing excessive re-rendering:

Sub-component

class TableHeader extends Component {
  handleClick = () => {
    this.props.onHeaderClick(this.props.value);
  }

  render() {
    return (
      <th onClick={this.handleClick}>
        {this.props.column}
      </th>
    );
  }
}

Main Component

{this.props.defaultColumns.map((column) => (
  <TableHeader
    value={column}
    onHeaderClick={this.handleSort}
  />
))}

ES5 Legacy Approach (Easy Way)

For ES5 compatibility, the following approach can pass values using .bind:

return (
  <th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);

By choosing the most appropriate technique, you can effectively pass values to onClick events in React and avoid the issue outlined in the question.

The above is the detailed content of How to Pass Values to onClick Events in React?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn