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);

  letclassName=child.props.className||'';
  if (router.pathname===props.href&&props.activeClassName) {
     className=`${className}${props.activeClassName}`.trim();
  }

  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">
     <a>About</a>
</Link>
That’s it