Reputation: 15
is it possible to have multiple activeClassName in NavLink component form react-router-dom?
I have Navbar with NavLinks and I need to add active class to the elements, with hasActiveClass === true, to render specific content. But also I need another active class (for example 'iconActive') to toggle icons, when the link is active. So the code is like that:
const MainNavComponent = () => (
<nav className="nav">
{menu.map(
({ ...props }, index) =>
<TileNav key={index} {...props} />
)}
</nav>
);
const TileNav = ({ to, hasActiveClass, exact, img, activeImg }) => {
// this is not working:
const isActive = element.className.contains('active');
const imgSrc = isActive ? activeImg : img;
return (
<NavLink
to={to}
activeClassName={
hasActiveClass ? 'active' : ''
}
className="tile-nav__link"
exact={exact}
>
<div className="tile-nav">
{isActive ? (
<img className="tile-nav__img" src={activeImg} alt="Menu icon" />
) : (
<img className="tile-nav__img" src={img} alt="Menu icon" />
)}
</div>
</NavLink>
)
};
and the data came from there:
const menu = [
{
to: '/',
img: menuAccessIcon,
activeImg: menuAccesActiveIcon,
exact: true,
hasActiveClass: false
},
{
to: urls.someUrl.url,
img: menuSomeIcon,
activeImg: menuSomeActiveIcon,
exact: true,
hasActiveClass: true,
hideForQuasiUser: true
},
{
to: urls.someurl.url,
img: menuSomeIcon,
activeImg: menuSomeActiveIcon,
exact: true,
hasActiveClass: true,
hideForQuasiUser: true
},
{
to: urls.someUrl.url,
img: menuIcon,
activeImg: menuActiveIcon,
exact: true,
hasActiveClass: true
}
];
I tried also add another key to each object: hasActiveIcon: true
and then:
activeClassName={
hasActiveClass ? 'active' : '',
hasActiveIcon && 'activeIcon'
}
but it still not working, because I got only second active class in DOM :( how can I fix it?
Upvotes: 0
Views: 981
Reputation: 12787
You can fix like this by using template strings
activeClassName={`${hasActiveClass ? "active" : ""} ${hasActiveIcon ? "activeIcon" : ""}`}
Upvotes: 0