I create a menu and want to highlight the item which i choose,and i did it. But when i press back/forward button,the menu item don\'t highlight. What should i do?
I ha
@Nadun's solution works for paths that don't contains arguments. If you're however using arguments in your routes, like me, here's a solution that should work for any route path, including /users/:id
or crazy stuff like /users/:id/whatever/:otherId
. It uses react-router's matchPath
API, which uses the exact same logic as the Router
component.
// file with routes
export const ROUTE_KEYS = {
ROOT: "/",
USER_DETAIL: "/users/:id",
};
export const ROUTES = {
ROOT: {
component: Home,
exact: true,
key: ROUTE_KEYS.ROOT,
path: ROUTE_KEYS.ROOT,
},
USER_DETAIL: {
component: Users,
key: ROUTE_KEYS.USER_DETAIL,
path: ROUTE_KEYS.USER_DETAIL,
},
};
.
// place within the App component
{Object.values(ROUTES).map((route) => (
))}
.
// MyMenu component
const getMatchedKey = (location) =>
(
Object.values(ROUTES).find((route) =>
matchPath(location.pathname, route)
) || {}
).path;
const MyMenu = ({ location }) => {
return (
Home
}
>
Some subitem
Users
}
>
User detail
);
};
export default withRouter(MyMenu);