Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render different components when active on Navlink

I'm using react-router's NavLink component to show a sidebar menu and inside the NavLink I have an icon. I want to change the icon so when the link is active the icon is filled. The code is somehting like this:

<NavLink
  to={route}
  exact
  activeClassName="selected"
>
  <Icon>{icon}</Icon>
</NavLink>

Is there a way to render different components inside a NavLink component?

like image 919
Khriz Avatar asked Jul 30 '18 10:07

Khriz


People also ask

What is the difference between link and NavLink in React-router-Dom?

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. And a is for external links.

Can we use Onclick in NavLink?

id=2 , etc when you click on it. It's a navlink with a onclick on it so we can refresh the id for the button "change page".


Video Answer


2 Answers

You can do something like this in your rendering function:

class YourComponent extends React.Component {
  render() {
    var isActive = this.context.router.route.location.pathname === this.props.to;

    return(
        <NavLink
          to={route}
          exact
          activeClassName="selected"
        >
         <Icon>{isActive && icon || otherIcon}</Icon>
        </NavLink>
    );
  }
}

NavLink.contextTypes = {
    router: PropTypes.object
};

This way you are actually checking if the route you are rendering is the active one and in case choose the correct Icon

like image 75
pinturic Avatar answered Sep 22 '22 13:09

pinturic


For a more independent component that will not need to be connected in a special way to context or redux. You could use withRouter, HOC element from react-router. After wrapping you have the match, location, history available for your component. So then you can check your route / to path string to the location object.

https://reacttraining.com/react-router/web/api/withRouter

like image 36
Luke Celitan Avatar answered Sep 22 '22 13:09

Luke Celitan