Create link with onClick event in Next.js

Create link with onClick event in Next.js
Photo by Chris Ainsworth / Unsplash

In Next.js, you can create a link with an onClick event using the Link component from the next/link module. The Link component allows you to navigate between pages on your website without triggering a full page reload.

Here's an example of how you might create a link with an onClick event:

import Link from 'next/link';

function handleClick(event) {
  event.preventDefault();
  // perform some action here
}

export default function MyComponent() {
  return (
    <Link href="/about">
      <a onClick={handleClick}>About</a>
    </Link>
  );
}

In this example, we're importing the Link component from next/link. We're also defining a handleClick function that takes an event as an argument. Inside the handleClick function, we're calling the preventDefault method on the event object to prevent the link from navigating to the new page. Then we wrap the link <a> tag with the Link component and passing the desired path of the route. Inside the <Link> component we have an <a> tag with onClick event and handleClick method as a callback.

You can replace the callback function with your own custom function and add your own event handling inside that.