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?
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.
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".
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With