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

187
Views
¿Cómo agregar un nombre de clase en React Js?

Estoy tratando de agregar un nombre de clase a la barra de navegación cuando el usuario se desplaza hacia abajo. Hice esto:

 var myNav = document.getElementById("nav"); window.onscroll = function() { "use strict"; if (document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150) { myNav.classList.add("scroll"); } else { myNav.classList.remove("scroll"); } };

Pero me dio un error:

 Cannot read properties of null (reading 'classList')

no se porque :(

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Obtiene ese error porque no existe ningún elemento con esa identificación. Tal vez no exista todavía , o tal vez nunca exista. Pero de cualquier forma, te recomiendo que evites mezclar react con manipulación directa del dom. La forma de reaccionar para hacer esto es escuchar el desplazamiento en un useEffect y luego establecer el estado:

 const NavBar = () => { const [scroll, setScroll] = useState(false); useEffect(() => { const handleScroll = () => { setScroll(document.body.scrollTop >= 150 || document.documentElement.scrollTop >= 150); } window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); } }, []); return ( <div id="nav" className={scroll ? "scroll" : undefined}> </div> ); }
about 4 years ago · Juan Pablo Isaza 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!