Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Cambiar el color de la barra de navegación con componentes de estilo de estado

Quiero cambiar el color de la barra de navegación en el desplazamiento, a través del enlace useState.

 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);

Estoy tratando de controlar el componente de estilo a continuación, ¿cómo controlo el fondo: prop con cualquier estado?

 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 answers
Answer question

0

Puedes pasar accesorios:

 <NavbarContainer bg={yourDynamicColor}> ... </NavbarContainer> const NavbarContainer = styled.div` background-color: ${props => props.bg}; // you can write any javascript, eg: color: ${({bg}) => bg === 'white' : 'black' : 'white'} `;
about 4 years ago · Santiago Trujillo Report

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 Report

0

Creo que la mejor manera es actualizar el nombre de clase de su componente según el estado. También inicie su eventListener en useEffect y elimínelo cuando se desmonte el componente.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!