0

I have the following code:

import React, {useState} from 'React';
import Header from './styles.js';

const HeaderComponent = props => 
{
  const [navBg, setNavBg] = useState(false);
  const isHome = props.name === 'Homepage' ? true : false;

  const changeNavBg = () =>
  {
   window.scrollY >= 800 ? setNavBg(true) : setNavBg(false);
  }

  window.addEventListener('scroll', changeNavBg);

  return (
  <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
  )
}

What I am trying to achieve is that when scrolling past 800px, I want my Header to change colors.

Cheers for your time.

1 Answer 1

4

Here's a couple of approaches you could try

1. Use the React onScroll UI event
 return (
   <div onScroll={changeNavBg}>
     <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
   </div>
 )
2. Consider binding the listener to a useEffect
import React, {useState} from 'React';
import Header from './styles.js';

const HeaderComponent = props => {
  const [navBg, setNavBg] = useState(false);
  const isHome = props.name === 'Homepage' ? true : false;

  const changeNavBg = () => {
   window.scrollY >= 800 ? setNavBg(true) : setNavBg(false);
  }

  useEffect(() => {
    window.addEventListener('scroll', changeNavBg);
    return () => {
      window.removeEventListener('scroll', changeNavBg);
    }
  }, [])

  return (
  <Header {...(isHome && navBg ? { backgroundColor: '#00008' : {})} />
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have actually managed to fix it by passing navBg as a prop in my styles.js and checking there if its set to true & isHome. I'll mark your answer as correct nonetheless as you deserve it for the given effort. Thank you.
Cool. Thanks. Anyways, here's a working example stackblitz.com/edit/react-jddnch?file=src/App.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.