Use 'active' state from React Router in Styled Components

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

提交回复
热议问题