protein
protein

Reputation: 37

Parallax scrolling in React

I have trouble implementing parallax scrolling in a background image in React, any help would be appreciated.

The error I get is:

TypeError: Cannot read property 'style' of null

function Hero() {
  const parallax = document.getElementById('home');
  window.addEventListener('scroll', function() {
    let offset = window.pageYOffset;
    parallax.style.backgroundPositionY = offset * .12 + 'px';
  })
  return (
    <div className="hero-container" id='home'>
      <p className='title'>The Burger Shop</p>
    </div>
  )
}
export default Hero
.hero-container {
  height: 100vh;
  background-image: url('burger2.jpg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
}

Upvotes: 2

Views: 1744

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

The element is not yet mounted at the time you run the getElementById.

You will need to use a ref (with useRef) and you will also need to remove the event listener once the element is un-mounted. You will need useEffect for this

function Hero() {
  const parallax = React.useRef(null);

  React.useEffect(() => {
    function scrollHandler() {
      const element = parallax.current;
      if (element) {
        let offset = window.pageYOffset;
        element.style.backgroundPositionY = offset * .12 + 'px';
      }
    }
    window.addEventListener('scroll', scrollHandler)
    // return the function to remove the handler
    // which will be run whn Hero is unmounted
    return () => window.removeEventListener('scroll', scrollHandler);
  }, []);
  
  return (
    <div className="hero-container" id='home' ref={parallax}>
      <p className='title'>The Burger Shop</p>
    </div>
  )
}
export default Hero

Demo at https://codesandbox.io/s/epic-water-fx5rb

Upvotes: 2

Related Questions