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
Susan SarandonOriginal
2024-12-06 03:59:14221browse

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>
);

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

Main component:

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

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!

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
Previous article:Clean Code SummaryNext article:Clean Code Summary