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
Release: 2024-11-28 13:57:12
Original
201 people have browsed it

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>
);
Copy after login

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>
    );
  }
}
Copy after login

Main component

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

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>
);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template