Search code examples
htmlcssreactjsstyled-components

Set className and create an action with styledComponents


Why does this not work? I want to give this NavigationTab in my NavigationBar a different backgroundcolor. Later when i select it the active tab should be displayed with a red Background. Like we know of different Navigation menues.

<NavigationLinkContainer className={"active"} onClick={() => { window.location.href = "/" }}>
const NavigationLinkContainer = styled.div`
    display: flex;
    flex-flow: row;
    align-items: center;
    box-sizing: border-box;
    transition: 0.3s ease-in-out;
    margin: 0px;
    cursor: pointer;
    height: 50px;


    .active {
        background-color: #D1495B; 

    }

    /* &:hover {
        background-color: ${colors.softRed};
    } */
    &:hover {
        color: ${colors.white};
        background: ${colors.softRed};


        &:before {
            height: 100%;
            transition: 0.3s ease-in-out;
        }
    }


    @media (max-width: 1000) {
        padding: 15px;
        border-bottom: 4px solid transparent;

        &:hover {
            background-color: azure;
        }

        &:active, &:hover {
            color: azure;
            border-bottom: 4px solid azure;
        }

        &:before {
            display: none;
        }
    }


`

Solution

  • You're not using the proper selector for the active class. Add the parent selector & to apply the style when the component has an active class.

    const NavigationLinkContainer = styled.div`
        display: flex;
        flex-flow: row;
        align-items: center;
        box-sizing: border-box;
        transition: 0.3s ease-in-out;
        margin: 0px;
        cursor: pointer;
        height: 50px;
    
        // use the parent selector &
        &.active {
            background-color: #D1495B; 
        }
    
       .
       .
       .
       . 
    
    `
    

    Hope this helps!