Active Menu Based On URL In Next.JS

How to the active menu based on URL in Next.JS?

How to the active menu based on URL in Next.JS?

In Next.JS the active link not so easy, so you just create a utility file such as ActiveLink.js & paste the below code into that

import { withRouter } from 'next/router';
import Link from 'next/link';
import React, { Children } from 'react';
const ActiveLink = ({ router, children, ...props }) => {
  const child=Children.only(children);

  if (router.pathname===props.href&&props.activeClassName) {

  delete props.activeClassName;

  return<Link{...props}>{React.cloneElement(child, { className })}</Link>;

export default withRouter(ActiveLink);

And now in the menubar import that utility file such as

import Link from '../../utils/ActiveLink';
and in the menu link addactiveClassName="active" such as
<Link activeClassName="active" href="/about">
That’s it

One Comment:

Leave a Reply

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