Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate React router active NavLink with child component

My menu currently looks like this:

<Menu>
    <MenuItem text="link1" />
    <MenuItem text="link2" />
</Menu>

To integrate with react-router-dom, I modified in the following way:

<Menu>

    <NavLink to="link1">
        <MenuItem text="link1" />
    </NavLink>

    <NavLink to="link2">
        <MenuItem text="link2" />
    </NavLink>

</Menu>

My MenuItem Component supports styling of the currently "active" link like so:

<MenuItem active text="link1" />

How do I integrate the "active" route styling with react-router-dom ?

Is there some boolean I can set in the following way?

<MenuItem active={isRouteActive} text="link1" />

Edit: MenuItem is a component from Blueprintjs. When the active prop is set, its possible some internal styling rules are applied to the component. I could use the activeClassName prop on NavLink but I don't want to replicate the css of a 3rd party component.

like image 292
Krimson Avatar asked Apr 22 '18 04:04

Krimson


People also ask

Should I use NavLink or link?

Conclusion. The NavLink is used when you want to highlight a link as active. So, on every routing to a page, the link is highlighted according to the activeClassName . Link is for links that need no highlighting.

How do I import NavLink into react Dom router?

Import NavLink into scope first: import { NavLink } from 'react-router-dom'; Then create the Navigation component just below the App component.


1 Answers

I ended up figuring it out. I created my own Component using composition of the Route component

const MenuItemExt = ({ icon, text, to, activeOnlyWhenExact }) => {
  return (
    <Route
      path={to}
      exact={activeOnlyWhenExact}
      children={({match, history}) => (
        <MenuItem
          active={match}
          icon={icon}
          onClick={() => {
            history.push(to);
          }}
          text={text}
        />
      )}
    />
  );
};
like image 72
Krimson Avatar answered Nov 14 '22 23:11

Krimson