Home > Software engineering >  Change Navbar Colour with State- Styled-Components
Change Navbar Colour with State- Styled-Components

Time:12-26

I want to change the colour of navbar on scroll, through the useState hook.

const Navbar = () => {

    const [colorChange, setColorchange] = useState(false);

    const changeNavbarColor = () =>{
       if(window.scrollY >= 38){
         setColorchange(true);
       }
       else{
         setColorchange(false);
       }
    };

    console.log(setColorchange)

    window.addEventListener('scroll', changeNavbarColor);

I am trying to drive the below styled component, how do I control the background: prop with any state?

const NavbarContainer = styled.div`
    width: 100%;
    height: 38px;
    background-color: red;
    margin-top: 10px;

    display: flex;
    justify-content: space-between;
    position: sticky;
    top:0;
    z-index: 1;
`;

CodePudding user response:

You can pass props:


<NavbarContainer bg={yourDynamicColor}>
 ...
</NavbarContainer>

const NavbarContainer = styled.div`
    background-color: ${props => props.bg};
    // you can write any javascript, e.g:
    color: ${({bg}) => bg === 'white' : 'black' : 'white'}
`;

CodePudding user response:

const NavbarContainer = styled.div`
    width: 100%;
    height: 38px;
    background-color: ${props => props.colorChange ? "red" : "blue"};
    margin-top: 10px;

    display: flex;
    justify-content: space-between;
    position: sticky;
    top:0;
    z-index: 1;
`;

CodePudding user response:

I think the best way is to update the className of your component based on the state. Also init your eventListener in useEffect and remove it when component unmount.

import React, { useEffect, useState } from 'react';

const Navbar = () => {
    const [colorChange, setColorchange] = useState(false);

    const changeNavbarColor = () => {
       if(window.scrollY >= 38){
         setColorchange(true);
       }
       else{
         setColorchange(false);
       }
    };

    useEffect(() => {
        window.addEventListener('scroll', changeNavbarColor);
        return () => {
            window.removeEventListener('scroll', changeNavbarColor);
        }
    }, [])
    
    return (
        <div className={colorChange ? 'colorBlack' : 'colorWhite'}>
            <p>Your navbar</p>
        </div>
    )
}

export default Navbar;

  • Related