We track sessions with cookies For what?
close

Select a language

<p><b>Top-3 libraries for animation in React</b></p>
August 24, 2022#tech

Top-3 libraries for animation in React

There are many ways to create an animation in React. For example, using CSS methods, but it's not serious. If your goal is to work with complex animations, it is better to study specialized libraries and platforms. In this article we will talk about the best and most popular three libraries for this purpose.

1. React Transition Group

Three things You should know about this library: 

- ReactTransitionGroup changes classes if the component lifecycle changes. At the same time, the animated style should be described in CSS classes. 

- ReactTransitionGroup has a very small size. It needs to be installed in a package for a React application, and the build will increase extremely slightly. In addition, you can use CDN.

- ReactTransitionGroup includes 3 components: CSSTransition, Transition and TransitionGroup. To start the animation, it is enough to wrap the component in them.

So, first import CSSTransitionGroup from react-transition-group. Then wrap the list and set the transitionName property. Every time a child element is added or removed in CSSTransitionGroup, it will receive animation styles.

<CSSTransitionGroup

    transitionName="example"

>

    {items}

</CSSTransitionGroup>

Note that if the transitionName = "example" property is set, the classes in your stylesheets will have to start with the name of the example.

.example-enter {

    opacity: 0.01;

}

.example-enter.example-enter-active {

    opacity: 1;

    transition: opacity 300ms ease-in;

}

.example-leave {

    opacity: 1;

}

.example-leave.example-leave-active {

    opacity: 0.01;

    transition: opacity 300ms ease-in;

}

}

This way you will be able to see the basic usage of the ReactTransitionGroup component. 

Now let's add logic. It is necessary to describe 2 methods for implementing an example of a contact list: 

1) handleAdd — adds new contacts by getting a random name and placing it directly in the state.items array. (if the name is random, the random-name package is used); 

2) handleRemove — the contact is deleted by index in the array state.items.

import React, { Component, Fragment } from 'react';

import { CSSTransitionGroup } from 'react-transition-group'

import random from 'random-name'

import Button from './button'

import Item from './item'

import './style.css';

export default class ReactTransitionGroup extends Component {

    constructor(props) {

        super(props);

        this.state = { items: ['Natividad Steen']};

        this.handleAdd = this.handleAdd.bind(this);

    }

    handleAdd() {

        let newItems = this.state.items;

        newItems.push(random());

        this.setState({ items: newItems });

    }

    handleRemove(i){

        let newItems = this.state.items.slice();

        newItems.splice(i,1);

        this.setState({items: newItems});

    }

    render () {

        const items = this.state.items.map((item, i) => (

            <Item

            item={item}

            key={i}

            keyDelete={i}

            handleRemove={(i) => this.handleRemove(i)}

            />

        ));

        return (

            <Fragment>

                <Button onClick={this.handleAdd}/>

                    <div className="project">

                        <CSSTransitionGroup

                        transitionName="example"

                        transitionEnterTimeout={500}

                        transitionLeaveTimeout={300}

                        >

                            {items}

                        </CSSTransitionGroup>

                    </div>

            </Fragment>

        );

    }

};

2. React Animation

React-animations is a library based on animations from animate.css. The library is relatively easy to use and includes many animation collections. Today, React-animation supports working with any inline style library that supports the use of objects to determine key animation frames, such as Aphrodite, Radium or styled-components.

First of all, we import the animation selected from react-animations.

After creating the component, we will wrap any HTML code or component to perform the animation.

Code example:

import React, { Component } from 'react';

import styled, { keyframes } from 'styled-components';

import { bounce } from 'react-animations';

import './style.css';

const Bounce = styled.div`animation: 2s ${keyframes`${bounce}`} infinite`;

export default class ReactAnimations extends Component {

    render() {

        return (

            <Bounce><h1>Hello Animation Bounce</h1></bounce>

        );

    }

}

3. React Move

A library for creating beautiful animations driven by React data. Allows you to define animations using the duration, delay and lightness functions. 

Features:

  • HTML animation, SVG React-Native;

  • animation lifecycle events: start, interrupt, end;

  • custom switching functions;

  • documentation with lots of examples;

  • supported in React, React-Native, React-VR;

  • compatible with TypeScript.

Code example from the official demo of this library:

import React, { PureComponent } from 'react'

import { NodeGroup } from 'react-move'

import Surface from 'docs/src/components/Surface' // this is just a responsive SVG

import { scaleLinear, scaleBand } from 'd3-scale'

import { easeExpInOut } from 'd3-ease'

import { ascending, max } from 'd3-array'

// **************************************************

//  SVG Layout

// **************************************************

const view = [1000, 450] // [width, height]

const trbl = [10, 10, 30, 10] // [top, right, bottom, left] margins

const dims = [ // Adjusted dimensions [width, height]

  view[0] - trbl[1] - trbl[3],

  view[1] - trbl[0] - trbl[2],

]

// **************************************************

//  Mock Data

// **************************************************

const letters = [

  { letter: 'A', frequency: 0.08167 },

  { letter: 'B', frequency: 0.01492 },

  { letter: 'C', frequency: 0.02780 },

  { letter: 'D', frequency: 0.04253 },

  { letter: 'E', frequency: 0.12702 },

  { letter: 'F', frequency: 0.02288 },

  { letter: 'G', frequency: 0.02022 },

  { letter: 'H', frequency: 0.06094 },

  { letter: 'I', frequency: 0.06973 },

  { letter: 'J', frequency: 0.00153 },

  { letter: 'K', frequency: 0.00747 },

  { letter: 'L', frequency: 0.04025 },

  { letter: 'M', frequency: 0.02517 },

  { letter: 'N', frequency: 0.06749 },

  { letter: 'O', frequency: 0.07507 },

  { letter: 'P', frequency: 0.01929 },

  { letter: 'Q', frequency: 0.00098 },

  { letter: 'R', frequency: 0.05987 },

  { letter: 'S', frequency: 0.06333 },

  { letter: 'T', frequency: 0.09056 },

  { letter: 'U', frequency: 0.02758 },

  { letter: 'V', frequency: 0.01037 },

  { letter: 'W', frequency: 0.02465 },

  { letter: 'X', frequency: 0.00150 },

  { letter: 'Y', frequency: 0.01971 },

  { letter: 'Z', frequency: 0.00074 },

]

const y = scaleLinear()

  .range([dims[1], 0])

  .domain([0, max(letters, (d) => d.frequency)])

class Example extends PureComponent {

  state = {

    sortAlpha: true,

  }

  update = () => {

    this.setState((state) => ({

      sortAlpha: !state.sortAlpha,

    }))

  }

  render() {

    const { sortAlpha } = this.state

    const sorted = letters.sort(sortAlpha ?

      (a, b) => ascending(a.letter, b.letter) :

      (a, b) => b.frequency - a.frequency,

    ).slice(0)

    const scale = scaleBand()

      .rangeRound([0, dims[0]])

      .domain(sorted.map((d) => d.letter))

      .padding(0.1)

    const width = scale.bandwidth()

   return (

      <div style={{ width: '100%' }}>

        <button onClick={this.update}>

          {`Sort ${sortAlpha ? 'Value' : 'Alpha'}`}

        </button>

        <Surface view={view} trbl={trbl}>

          <NodeGroup

            data={sorted}

            keyAccessor={(d) => d.letter}

            start={() => ({

              opacity: 1e-6,

              x: 1e-6,

            })}

            enter={(d) => ({

              opacity: [0.7],

              x: [scale(d.letter)],

              timing: { duration: 750, ease: easeExpInOut },

            })}

            update={(d, i) => ({

              opacity: [0.7],

              x: [scale(d.letter)],

              timing: { duration: 750, delay: i * 50, ease: easeExpInOut },

            })}

            leave={() => ({

              opacity: [1e-6],

              x: [scale.range()[1]],

              timing: { duration: 750, ease: easeExpInOut },

            })}

          >

            {(nodes) => (

              <g>

                {nodes.map(({ key, data, state: { x, opacity } }) => (

                  <g key={key} transform={`translate(${x},0)`}>

                    <rect

                      height={dims[1] - y(data.frequency)}

                      y={y(data.frequency)}

                      fill="#ff69b4"

                      width={width}

                      opacity={opacity}

                    />

                    <text

                      x={scale.bandwidth() / 2}

                      y={dims[1] + 15}

                      dx="-.35em"

                      fill="#dadada"

                    >{data.letter}</text>

                  </g>

                ))}

              </g>

            )}

          </NodeGroup>

        </Surface>

      </div>

    )

  }

}

export default Example

Thus, in this article we have analyzed some of the best libraries for implementing animations in React, learned about their key features and the possibilities of their application, and also learned how to implement these technologies in their projects.