Use 'active' state from React Router in Styled Components

前端 未结 9 1671
北海茫月
北海茫月 2021-02-15 12:24

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

相关标签:
9条回答
  • 2021-02-15 12:56

    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).

    0 讨论(0)
  • 2021-02-15 12:56

    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>;
    
    0 讨论(0)
  • 2021-02-15 12:57
    const StyledLink = styled(NavLink)`
      color: blue;
    
      &.active {
        color: red;
      }
    `;
    
    0 讨论(0)
提交回复
热议问题