Use 'active' state from React Router in Styled Components

前端 未结 9 1669
北海茫月
北海茫月 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
    }) => )({
      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).

提交回复
热议问题