Home > Back-end >  How to get the current pathname correctly in React Router v6?
How to get the current pathname correctly in React Router v6?

Time:05-24

Edit how-to-get-the-current-pathname-correctly-in-react-router-v6

If you prefer keeping the path matching localized to the parent component, import and use the useLocation hook and matchPath utility from react-router-dom.

Example:

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

...

const { pathname } = useLocation();

...

<div>
  {listItems.map((item) => (
    <ListItemButton
      component={NavLink}
      to={item.path}
      selected={matchPath(item.path, pathname)}
    >
      {item.label}
    </ListItemButton>
  ))}
</div>

  • Related