Categories
React Answers

How to add onClick event handler with React?

Spread the love

Sometimes, we want to add onClick event handler with React.

In this article, we’ll look at how to add onClick event handler with React.

How to add onClick event handler with React?

To add onClick event handler with React, we set the onClick prop of an element to a function that runs when we click on the element.

For instance, we write

const ActionLink = () => {
  const handleClick = (e) => {
    e.preventDefault();
    console.log("The link was clicked.");
  };

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
};

to set the onClick prop of the a element to the handleClick function.

In handleClick, we call e.preventDefault to prevent the default action of navigating to the URL set as the value of the href attribute.

Then we call console.log to log some text.

Conclusion

To add onClick event handler with React, we set the onClick prop of an element to a function that runs when we click on the element.

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 *