cssreactjsscrollbackground

the react background image changes depending on the components I would like to know how to do that


I'm learning and I saw the tomorrowland site and I would like to reproduce it, only on the home page there is this background scrolling effect which changes depending on the component I don't know how to code it and I need your help

import './App.css';
import Hero from './components/hero/Hero';

function App() {
  return (
    <div className="app">
      <div className="Blobs_blobs__cW0d3">
        <img src="/images/principal_bg.jpg" className="Blobs_backgroundImage__ciJQh Blobs_visible__EJ_Hc" alt="default background" />
        <img src="/images/bleu_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Belgium background" />
        <img src="/images/blanc_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Winter background" />
        <img src="/images/violet_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Brasil background" />
        <img src="/images/rouge_bg.jpg" className="Blobs_backgroundImage__ciJQh" alt="Owr background" />
      </div>
      <div className='appContainer'>
        <Hero />
        <Hero />
        <Hero />
        <Hero />
        <Hero />
      </div>
    </div>
  );
}

Solution

  • Set up a state to store the background color and set the state during different scroll positions.

    Something like this:

    Set your initial state. On the TL website its an orangy color so i'll use that

    const [backgroundColor, setBackgroundColor] = useState('orange');
    

    Have a 'scroll' event listener on mount and removes it on unmount to avoid memory leaks.

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
          window.removeEventListener('scroll', handleScroll);
        };
    }, []);   // on mount
    

    Then some function that checks scroll position and updates the backgroundColor state accordingly.

    const handleScroll = () => {
        const scrollPosition = window.scrollY;
        if (scrollPosition < 100) {
          setBgColor('white');
        } else if (scrollPosition < 200) {
          setBgColor('lightblue');
        } else if (scrollPosition < 300) {
          setBgColor('lightgreen');
        } else {
          setBgColor('lightcoral');
        }
    };
    

    All you have to do for your HTML div styling.

    // Your container/background div wrapping whatevers inside.
    <div style={{ height: '2000px', backgroundColor: backgroundColor }}>
        <div style={{ height: '200px', backgroundColor: 'black' }}>
    <div style={{ height: '200px', backgroundColor: backgroundColor }}>
    

    Good luck.