React Scroll Parallax

website·Indexed 33 days ago

https://react-scroll-parallax.damnthat.tv/

React hooks and components for creating scroll-driven parallax effects via WAAPI (v4 beta). Features include the <Parallax /> and <ParallaxBanner /> components, the useParallax() hook, and support for horizontal scrolling, custom CSS variable effects, and easing animations via cubic-bezier curves.

Tokens
6K
Snippets
33
Records
37
Agent score
65%

What's inside React Scroll Parallax

  1. Apply scroll effects with the Parallax component

    The Parallax component is the primary tool for applying scroll-driven effects. It accepts all parallax configuration props (managed by parallax-controller) and passes non-parallax props (like style and className) directly to the underlying div element.
    import { Parallax } from 'react-scroll-parallax';
    
    const Example = () => (
      <>
        {/* Speed Control: Simplest way to achieve parallax effect */}
        <Parallax speed={-5}>
          <div>Slows down</div>
        </Parallax>
        
        <Parallax speed={5}>
          <div>Speeds up</div>
        </Parallax>
    
        {/* Translate Controls: Fine-tuned start and end transforms */}
        {/* Values without units default to % (e.g., -20 becomes -20%) */}
        <Parallax translateY={[-20, 10]}>
          <div>Moves from -20% to 10% translateY</td>
        </Parallax>
    
        {/* Custom styling and children */}
        <Parallax style={{ background: 'blue' }} className="test">
          Hello
        </Parallax>
      </>
    );
  2. Implement a multi-layer horizontal parallax effect

    To create a horizontal parallax effect with multiple layers (e.g., a background and foreground), stack layers absolutely within a container. Assign different speed values to each layer to create depth—higher speeds move faster. To prevent edges from appearing during movement, extend the left and right CSS properties. Use a targetElement (via a ref to the container) in the useParallax hook to ensure the progress rate is calculated consistently across all layers.
    function DemonWoods() {
      const target = useRef(null);
    
      const mid = useParallax({
        speed: 50,
        targetElement: target.current,
      });
      const close = useParallax({
        speed: 100,
        targetElement: target.current,
      });
    
      const midExtend = 50 * 5 * -1;
      const closeExtend = 100 * 5 * -1;
    
      return (
        <div ref={target} style={{ position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', left: midExtend, right: midExtend }} className="mid-layer" />
          <div style={{ position: 'absolute', left: closeExtend, right: closeExtend }} className="close-layer" />
        </div>
      );
    }
  3. Create scroll effects using the Parallax component

    The <Parallax /> component wraps children and applies effect styles to a managed div rather than the children themselves. It supports CSS transform props like translateX and translateY. When providing arrays for these props (e.g., [-20, 20]), percentages are assumed if no unit is specified.
    import { Parallax } from 'react-scroll-parallax';
    
    const Component = () => (
      <>
        {/* Example: translateY from -20% to 20% */}
        <Parallax translateY={[-20, 20]}>
          <div>Content 1</div>
        </Parallax>
    
        {/* Example: translateX from -100px to 200px */}
        <Parallax translateX={['-100px', '200px']}>
          <div>Content 2</div>
        </Parallax>
      </>
    );
  4. Manage parallax cache with useParallaxController

    The useParallaxController hook provides access to the ParallaxController instance via React context. It must be used within a <ParallaxProvider>. This is primarily used to manually trigger a cache update when the page layout changes (e.g., after an image loads or a route changes).
    import { useParallaxController } from 'react-scroll-parallax';
    
    function Image(props) {
      const parallaxController = useParallaxController();
    
      // Update cached values after image dimensions have loaded
      const handleLoad = () => parallaxController.update();
    
      return <img onLoad={handleLoad} src="..." />;
    }
    
    // Example: Update controller on route change
    function useUpdateControllerOnRouteChange() {
      const location = useLocation();
      const parallaxController = useParallaxController();
    
      useEffect(() => {
        parallaxController.update();
      }, [location.pathname]);
    }
  5. Create custom scroll effects using CSS variables

    You can animate any CSS property based on an element's scroll position by using the onProgressChange callback within the useParallax hook. This callback provides a progress value (typically between 0 and 1) which can be assigned to a CSS variable on the element's style object. You can then reference this variable (e.g., var(--progress)) in your CSS files or inline styles to drive animations for properties like letter-spacing, text-shadow, or opacity.
    function Example() {
      const parallax = useParallax({
        onProgressChange: (progress) => {
          if (parallax.ref.current) {
            // set progress to CSS variable
            parallax.ref.current.style.setProperty(
              '--progress',
              progress.toString()
            );
          }
        },
      });
    
      return (
        <div ref={parallax.ref}>
          Hello World
        </div>
      );
    }
  6. Implement basic parallax movement using the speed prop

    The speed prop is an abstraction for applying translateY (vertical scroll) or translateX (horizontal scroll) effects. Each increment of 1 in the speed value increases the translation effect by 10px. For example, in a vertical scroll, speed: 10 is equivalent to translateY: ['100px', '-100px'].
    <Parallax speed={-10} />
    <Parallax speed={10} />
  7. Install react-scroll-parallax v4 beta

    Install the v4 beta version of react-scroll-parallax, which uses the Web Animations API for scroll-driven animations. Note that Firefox does not currently support the Web Animations ViewTimeline API by default; a polyfill is required for Firefox support.
    npm install react-scroll-parallax@beta
  8. Create parallax banners with ParallaxBanner

    The <ParallaxBanner> component creates a container for layering images or custom markup with scroll effects.

    Critical Requirements:

    • You must provide a height or aspectRatio via style or className, otherwise the banner will be hidden.
    • Layer order matters: the first element/layer is at the bottom; the last is on top.

    Banners can be configured using the layers prop or by nesting <ParallaxBannerLayer> components.

    import { ParallaxBanner, ParallaxBannerLayer } from 'react-scroll-parallax';
    
    // Option 1: Using ParallaxBannerLayer children
    <ParallaxBanner style={{ aspectRatio: '2 / 1' }}>
      <ParallaxBannerLayer image="https://foo.com/foo.jpg" speed={-20} />
      <ParallaxBannerLayer>
        <h1>My Headline</h1>
      </ParallaxBannerLayer>
    </ParallaxBanner>
    
    // Option 2: Using the layers prop
    <ParallaxBanner
      style={{ aspectRatio: '2 / 1' }}
      layers={[
        { image: 'https://foo.com/foo.jpg', speed: -20 },
        { children: 'My Headline', speed: -10 },
      ]}
    />
  9. Apply CSS scroll effects with start and end values

    CSS effects are defined using an array containing a start value and an end value. An optional third value can be provided to set a specific easing function for that effect.

    Progress is determined by the element's position relative to the viewport: the effect starts when the top of the element enters the bottom of the view and ends when the bottom of the element exits the top of the view.

    useParallax({
      // Translate Y from -100% to 100% with ease-in
      translateY: [-100, 100, 'ease-in'],
      // Scale from 0 to 1 with a custom cubic-bezier
      scale: [0, 1, 'cubic-bezier(0.2, -0.67, 1, -0.62)']
    });
  10. Setup the ParallaxProvider root wrapper

    The ParallaxProvider must wrap your application root to provide the ParallaxController via React context. It should be placed in a component that does not unmount during route changes (e.g., an AppContainer).
    import { ParallaxProvider } from 'react-scroll-parallax';
    
    const AppContainer = () => (
      <ParallaxProvider>
        <Router>
          <App />
        </Router>
      </ParallaxProvider>
    );
  11. Apply parallax effects with useParallax

    The useParallax hook is the primary way to apply parallax effects to a DOM element. You must assign the returned ref to the target element and provide a configuration object (such as speed) to define the effect.
    import { useParallax } from 'react-scroll-parallax';
    
    function Component() {
      // speed: 10 defines the parallax effect
      const { ref } = useParallax<HTMLDivElement>({ speed: 10 });
      return <div ref={ref}>Parallax Element</div>;
    }
  12. Create scroll effects using the useParallax hook

    The useParallax hook allows you to apply parallax effects directly to an element by attaching the returned ref. Effect styles are applied directly to the element the ref is attached to. You can pass configuration props such as speed or CSS transform properties to the hook.
    import { useParallax } from 'react-scroll-parallax';
    
    const Component = () => {
      // Example: speed up the rate of scroll
      const { ref } = useParallax({ speed: 10 });
      return <div ref={ref}>Content</div>;
    };