How to create Scrolling Transformations for your React App?
Published: 2021-03-23 14:19:32

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)](https://www.creative-tim.com/blog/web-design/web-design-trends/?ref=devto).

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](https://creativetimblog.com/blog/wp-content/uploads/2020/03/scrolling-trasnformation.gif)
######[Source: dribbble.com](https://dribbble.com/shots/14669566-Landing-page-design-for-Qoorio)
&nbsp;
##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 <ScrollAnimation>. 
* 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>

)
```
* Relies on CSS animations, so cannot be controlled using JavaScript
* Check out these examples:
![example 1](https://creativetimblog.com/blog/wp-content/uploads/2020/03/animation-react.gif)
![example 2](https://creativetimblog.com/blog/wp-content/uploads/2020/03/react-transformation-app.gif)

######[Source](https://dbramwell.github.io/react-animate-on-scroll/#initiallyVisible)
&nbsp;

*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 >
```
* Check out the props that can be used with react-reveal.
&nbsp;
###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} />
```
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)

}, [])
```
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

  }

}
```
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;
```
  &nbsp;
###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} />
```
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>

  )

}
```

###**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](https://github.com/tj/consolidate.js/#supported-template-engines). Creative Tim also offers a [huge number](https://www.creative-tim.com/templates/react?ref=devto) 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](https://www.creative-tim.com/product/material-dashboard-react?ref=devto) to the paid [NextJS Argon Dashboard PRO](https://www.creative-tim.com/product/nextjs-argon-dashboard-pro?ref=devto) 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](https://www.creative-tim.com/?ref=devto) today!