React Router adds an active
class to NavLinks when you are on the page that they link to. How can I access this property with Styled Components. I need to styled me
As of react-router
v4, you can style the active state of NavLink
without any dependencies using activeClassName
and Styled Components' attrs()
function:
export const StyledNavLink = styled(NavLink).attrs({
activeClassName,
})`
&.${activeClassName} {
background: red;
}
`;
Related documentation:
Styled component:
import { NavLink } from 'react-router-dom';
export const MyNavLink = styled(NavLink)`
&.${props => props.activeClassName} {
color: red;
}
`;
Usage:
<MyNavLink to="/dashboard" activeClassName="anyClassNameWillWork">Dashboard</MyNavLink>
Tested with:
react-router-dom 5.1.2
styled-components 5.0.1
The prop className is getting added to the children of NavLink and so its not accessible at NavLink level. The docs were not clear about this. Therefore, we cannot check for props.className === 'active' and add styles.
Instead, you could just resort to css inside styled components for your use:
const LinkElem = styled(NavLink)`
// example style
&.active {
color: ${props => props.theme.orange }
}
`;
If you are using object syntax in styled-components, you can implement the next solution:
const activeClassName = 'nav-item-active'
export const StyledLink = styled(NavLink).attrs({
activeClassName,
})(props => ({
height: '20px',
width: '20px',
backgroundColor: 'green',
['&.' + props.activeClassName]: {
backgroundColor: 'red'
}
}))
You can check a live example in the next StackBlitz project:
https://stackblitz.com/edit/react-hcudxz
I think it's simplest decision.
const StyledLink = styled(NavLink)`
color: blue;
&.${props => props.activeClassName} {
color: red;
}
`;
The string you added to NavLink's activeClassName
will join to className
later when you hit the specific route. Since styled components support pure css,
&.{yourActiveClassName} { #css goes here}
should work.