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

How to Pass Values to onClick Events in React JS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 13:57:12198browse

How to Pass Values to onClick Events in React JS?

Passing Values to onClick Events in React JS

React's onClick event handler doesn't directly allow for value passing. When clicked, it displays a SyntheticMouseEvent object on the console. To pass values effectively, follow these solutions:

Easy Way

Use an arrow function:

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

This creates a function that invokes handleSort with the desired parameters.

Better Way

Extract the code into a sub-component:

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

This ensures re-rendering only when necessary.

Old Easy Way (ES5)

Bind the function to the Component context:

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

The above is the detailed content of How to Pass Values to onClick Events in React JS?. 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