Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 'active' state from React Router in Styled Components

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 menu items differently when you are on their page.

const LinkElem = styled(NavLink)`
  font-size: 16px;
  font-weight: 400;

  ${props => console.log(props)};

  &:hover {
    color: ${props => props.theme.colorOrange};
  }
`;

const Menu = props => {
  const { me } = props;
  return (
    <MenuElem>
      <li>
        {me ? (
          <LinkElem to="/account">Account</LinkElem>
        ) : (
          <LinkElem to="/login">Log in / sign up</LinkElem>
        )}
      </li>
    </MenuElem>
  );
};
like image 616
Evanss Avatar asked May 07 '18 06:05

Evanss


People also ask

Does styled-components use JSS?

Styled-JSS implements a styled-primitives interface on top of JSS. Its API is similar to styled-components but thanks to the JSS core, it supports all features and plugins JSS does. For e.g. you can use full JSON Syntax inside.

Can you use styled-components with SCSS?

In SCSS, you can use variables and formulas for expressing colors, font sizes, widths and spacing variants. However, when you switch from SCSS to styled components, the syntax isn't valid anymore. Styled component files are CSS-in-JS, so they are actually JavaScript files.


2 Answers

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 }
  }
`;
like image 87
Anu Avatar answered Nov 25 '22 20:11

Anu


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()
like image 23
syntagma Avatar answered Nov 25 '22 22:11

syntagma