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>