Categories
React Answers

How to use onClick event on Link with React?

Spread the love

To use onClick event on Link with React, we replace the Link with a regular element.

For instance, we write

selectName = (name) => {
  this.setState({ selectedName: name }, () => {
    this.props.history.push("about");
  });
};

//...

<li key={i} onClick={() => selectName(name)}>
  {name}
</li>

to create the selectName method that calls this.props.history.push to navigate to the 'about' URL.

And we set the onClick prop of the li to a function that calls selectName with name to call it when we click on the li.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *