How to compare the current pathname and route in next.js?

Viewed 828

I am currently migrating a project which was created with creat-react-app to a next.js project.

One thing that I faced into is to migrate the matchPath function from react-router-dom to somewhat next.js function comparing the current pathname and a kind of passed href route name so as to realize and select a current nav item.

import { useLocation, matchPath } from 'react-router-dom';

const NavBar = ({ item, pathname }) => {
  const open = matchPath(pathname, {
    path: item.href,
    exact: false
  });
  ...
}

I was able to get the current pathname using next/router, but after that, I have no idea how to compare them.

import { useRouter } from 'next/router';

const NavBar = () => {
  const { pathname } = useRouter();

  ...
}

In this case, how to figure it out?

Thanks in advance.

1 Answers
import { useRouter } from 'next/router';

const NavBar = () => {
  const { pathname } = useRouter();
  const parts = pathname.split('/');
  const match = parts[parts.length - 1];
  const open = match === 'blogs' //or whatever
  ...

}
Related