How to use the onClick event on React router link?

Estimated read time 1 min read

In React, you can use the onClick event on a Link component from React Router to execute a JavaScript function when the link is clicked. Here’s an example:

import React from 'react';
import { Link } from 'react-router-dom';

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

  return (
    <Link to="/" onClick={handleClick}>
      Go home
    </Link>
  );
}

In this example, we define a function called handleClick() that logs a message to the console when called. We then define a Link component from React Router that links to the home page (to="/") and attach the onClick event to it. The onClick event calls the handleClick() function when the link is clicked.

Note that you need to import the Link component from React Router to use it in your code. Also, make sure to wrap your app with the BrowserRouter component from React Router to enable client-side routing.

You can use the onClick event on a Link component 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 component.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply