Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Change Navbar Colour with State- Styled-Components

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;
`;
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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'}
`;
about 4 years ago · Santiago Trujillo Relatório

0

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;
`;
about 4 years ago · Santiago Trujillo Relatório

0

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;

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda