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
}) => )({
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).