Use 'active' state from React Router in Styled Components

前端 未结 9 1633
北海茫月
北海茫月 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:33

    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()
    0 讨论(0)
  • 2021-02-15 12:34

    Styled component:

    import { NavLink } from 'react-router-dom';
    
    export const MyNavLink = styled(NavLink)`
      &.${props => props.activeClassName} {
        color: red;
      }
    `;
    

    Usage:

    <MyNavLink to="/dashboard" activeClassName="anyClassNameWillWork">Dashboard</MyNavLink>
    

    Tested with:

    react-router-dom 5.1.2
    styled-components 5.0.1

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

    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 }
      }
    `;
    
    0 讨论(0)
  • 2021-02-15 12:42

    If you are using object syntax in styled-components, you can implement the next solution:

    const activeClassName = 'nav-item-active'
    
    export const StyledLink = styled(NavLink).attrs({
        activeClassName,
    })(props => ({
        height: '20px',
        width: '20px',
        backgroundColor: 'green',
        ['&.' + props.activeClassName]: {
            backgroundColor: 'red'
        }
    }))
    
    • Declare variable with the name of the active class of react router
    • Style the NavLink and pass as attribute activeClassName
    • From the props get the activeClassName
    • Declare the conditional styles in case of the activeClassName being present

    You can check a live example in the next StackBlitz project:

    https://stackblitz.com/edit/react-hcudxz

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

    I think it's simplest decision.

    const StyledLink = styled(NavLink)`
      color: blue;
    
      &.${props => props.activeClassName} {
        color: red;
      }
    `;
    
    0 讨论(0)
  • 2021-02-15 12:53

    The string you added to NavLink's activeClassName will join to className later when you hit the specific route. Since styled components support pure css,

    &.{yourActiveClassName} { #css goes here}
    

    should work.

    0 讨论(0)
提交回复
热议问题