Home > Web Front-end > JS Tutorial > How Can I Pass a Value to an onClick Event in React?

How Can I Pass a Value to an onClick Event in React?

Susan Sarandon
Release: 2024-12-06 03:59:14
Original
218 people have browsed it

How Can I Pass a Value to an onClick Event in React?

React js: Passing Value to onClick Event

In React, accessing onClick event value properties can be challenging, displaying console messages like "SyntheticMouseEvent {...}" instead of the desired value. This can be resolved by understanding React's event handling mechanism and employing appropriate techniques.

Easy Way

To pass a value to the onClick event using an arrow function, follow this approach:

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

This creates a new function that calls handleSort with the correct parameters.

Better Way

For optimal performance, it's recommended to extract the onClick handling into a sub-component. This way, the handler reference won't change and unnecessary re-renders will be avoided.

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

The above is the detailed content of How Can I Pass a Value to an onClick Event in React?. 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