DEV Community

Cover image for How to create Scrolling Transformations for your React App?
Creative Tim
Creative Tim

Posted on • Originally published at creative-tim.com

How to create Scrolling Transformations for your React App?

With more and more users looking for realistic designs that are more focused on purpose rather than just design, a lot of web design trends are becoming increasingly popular in 2021. One of these trends that have been gathering a lot of momentum is scrolling transformations (no. 16).

Scrolling transformations as the name suggests are all about allowing users to engage and interact with your website by letting them digest as much or as little of your website’s content as they wish by focusing on a good scrolling experience. Most sites that feel interactive have some sort of scrolling animation that can include animations like fade-in/out or parallax effect of items moving at different speeds.

Since it is established that a good scrolling experience is a trend for website developers, let’s get into the ways using which you can create scrolling transformations for your React app.

scrolling transformations

Source: dribbble.com

 

How to create Scrolling Transformations for your React App?

Creating scrolling transformations for your React app requires you to use some available libraries, and then use them to trigger scroll animations based on the position of the element and the position of the scroll.

I. React Libraries for Scrolling Transformations

react-animate-on-scroll

  • Uses animate.css to power animations
  • Uses a single React component called .
  • Usage:

1 - Pass a CSS animation-name as a property for the component
2 - Example:

import ScrollAnimation from ‘react-animate-on-scroll’

const Animation = () => (

<ScrollAnimation animateBounce=”bounceIn”>

<p>Text bounces in on scroll</p>

</ScrollAnimation>

)
Enter fullscreen mode Exit fullscreen mode
  • Relies on CSS animations, so cannot be controlled using JavaScript
  • Check out these examples: example 1 example 2
Source

 

react-reveal

  • A comparatively more robust library that uses browser APIs
  • Uses CSS based animations to which animation properties can be applied using React’s inline-style
  • Usage:

1 - Each animation has its own component which can be imported and used in default without using props.
2 - Example:

import Rotate from ‘react-reveal/Rotate’

;<Rotate>

  <p>Text rotates on scroll</p>

</Rotate >
Enter fullscreen mode Exit fullscreen mode
  • Check out the props that can be used with react-reveal.   ###II. Creating Scrolling Transformations: The Basic Method Now that you are aware of the libraries that can help achieve scrolling transformations, it is important to understand how these core libraries can trigger scrolling animations in React.

1 - Create a “ref” in React to keep track of the element

const refRef = useRef(null)

return <div ref={refRef} />
Enter fullscreen mode Exit fullscreen mode

2 - Run the code before the component mounts by using useLayoutEffect. The scroll event listener and the function that runs when the user scrolls should be attached here.

useLayoutEffect(() => {

  window.addEventListener(‘scroll’, onScroll)

  return () => window.removeEventListener(‘scroll’, onScroll)

}, [])
Enter fullscreen mode Exit fullscreen mode

3 - Check the user’s scroll position in the scroll function OnScroll. You can do this by adding the Y position of the user to the height of the page. Grab the “ref” of the animated element and check the Y coordinate of its top using getBoundingClientRect() API. Finally, check a user’s scroll action by knowing if the scroll position is greater than the top of the element.

const topPos = refRef.current.getBoundingClientRect().top

const onScroll = () => {

  const scrollPos = window.scrollY + window.innerHeight

  if (topPos < scrollPos) {

    // enter animation code here

  }

}
Enter fullscreen mode Exit fullscreen mode

4 - Use React’s inline styles or Styled Components to create simple animations.

The following example code creates a “fade in” animation.

const [show, doShow] = useState({

  itOne: false,

  itTwo: false,

  itThree: false,

})

const refRef = useRef(null)

return (

  <>

    <Div animate={show.itOne} ref={refRef} />

  </>

)

// component we are animating

const Div = styled.div`

  transform: translateX(${({ animate }) => (animate ? ‘0’ : ‘-50vw’)});

  transition: transform 1s;

  height: 650px;

  width: 250px;

  background-color: green;
Enter fullscreen mode Exit fullscreen mode

 

III. Creating Scrolling Transformations: The Advanced Method

There is yet another way to calculate the scroll position relative to an element. This can be achieved using the Intersection Observer API. You can use the threshold to do so. This is possible if you do not need to support IE as a target platform.

const ref = useRef(null);

const callback = entry => {

    // Get intersection data here

    // Like entry.intersectionRatio

    // Here we can set state or update ref

    // based on entry data

};

const observer = new IntersectionObserver(callback, {

      root: this.ref.current,

            // Creates a threshold of with increments of 0.01

      threshold: new Array(101).fill(0).map((v, i) => i * 0.01),

    });

  }

useEffect(() => {

    observer.observe(ref.current)

})

return <div ref={ref} />
Enter fullscreen mode Exit fullscreen mode

You can also use the react-intersection-observer library to calculate scroll positions using a hook. The hook generates a “ref” and a Boolean called inView that tells you if the element has been scrolled.

import React from ‘react’

import { useInView } from ‘react-intersection-observer’

const Component = () => {

  const { ref, inView, entry } = useInView({

    /* Optional options */

    threshold: 0,

  })

  return (

    <div ref={ref}>

      <h2>{`Header inside viewport ${inView}.`}</h2>

    </div>

  )

}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Now that you are well equipped with the knowledge required to trigger scrolling transformations in React, there are some examples that you can easily execute. You can make the scroll animation interactive with the scroll, instead of making it a one-time animation. This can be achieved by setting up the scroll function to change the react state from 0 to 100 based on the element position on the screen.

You can also change the Styled Component into Object Style to optimize them, especially in cases when fast scrolling leads to errors in the console of Styled Components. You can also enable “sticky” scrolling by nesting a “caption” inside a container so that the caption sticks to the bottom of the container when scrolling.

In conclusion, there are a huge number of options that you can tweak as per your need to give a seamless scrolling experience to your user. Check out this example. Creative Tim also offers a huge number of React Themes and templates that give you the freedom of choosing and combining components to create an immaculate website. All themes ranging from the free Material Dashboard React to the paid NextJS Argon Dashboard PRO have been created to offer premium themes and modern styling for all your website development themes.
Jumpstart your path to easier and better website development with Creative Tim today!

Top comments (1)

Collapse
 
sm0ke profile image
Sm0ke

Nice, thanks for sharing!