Use 'active' state from React Router in Styled Components

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:

  • activeClassName
  • attrs()

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 }
  }
`;

const StyledLink = styled(NavLink)`
  color: blue;

  &.active {
    color: red;
  }
`;