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
I'm not particularly keen on the &.active
approach if you're trying to build a styled-component that is router independent, so I created asNavLink to deal with this:
npm install as-nav-link --save
Given a component:
const MyNavAnchor = styled(({
as: T = 'a',
active, // destructured so it is not passed to anchor in props
...props
}) => <T {...props} />)({
textDecoration: 'blink',
color: 'blue',
}, ({ active }) => (active && {
color: 'red',
}));
You can use it like this:
import asNavLink from 'as-nav-link';
const MyNavLink = asNavLink(config)(MyNavAnchor);
And it will pass down the active prop to your styled component.
config
is optional and can include an isActive
function (as per ReactRouter's NavLink) and an activeProp
string (the prop name that is passed to your component).
react-router now has activeStyle
props, which can be used to style active link easily:
<NavLink
to="/faq"
activeStyle={{
fontWeight: "bold",
color: "red"
}}
>
FAQs
</NavLink>
With styled-components:
const LinkElem = styled(NavLink)`
font-size: 16px;
font-weight: 400;
`;
<LinkElem
activeStyle={{
fontWeight: 'bold',
color: 'red',
}}
></LinkElem>;
const StyledLink = styled(NavLink)`
color: blue;
&.active {
color: red;
}
`;