How to use the onClick event on link with React?

Estimated read time 1 min read

In React, you can use the onClick event on a link (<a> tag) to execute a JavaScript function when the link is clicked. Here’s an example:

import React from 'react';

function MyComponent() {
  function handleClick() {
    console.log('Link clicked!');

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

In this example, we define a function called handleClick() that simply logs a message to the console when called. We then define a link (<a> tag) and attach the onClick event to it. The onClick event calls the handleClick() function when the link is clicked.

Note that we also include href="#" in the link to make sure it is clickable. If you leave out the href attribute or set it to an empty string, the link may not be clickable.

You can use the onClick event on a link to perform any action you want, such as navigating to a different page or showing a modal. Just define a function to handle the event and attach it to the onClick attribute of the link.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply