August 18, 2019

React animations with Anime.js

React animations with Anime.js

Anime.js is a lightweight javascript animation library that is very simple to use. Due to its simplicity it's also very easy to use with React.js and is a very good alternative to other libraries.

Let's have first a short look at the library itself and how to use it on a simple example similar to the ones mentioned in their documentation.

HTML:

<div id="target" class="square"></div>

CSS:


.square {
    width: 50px;
    height: 50px;
    background: red;
}

Javascript:

anime({
  targets: '#target',
  translateX: 250
});

As we can see in the example we call anime and pass in an object with the configuration of the animation, the first key "targets" expects either the id or class of an HTML element. But what makes Anime.js very flexible is that we can even pass a DOM Node or a entire Nodelist as target. Below is the same example modified with a Nodelist assuming we add more HTML elements with the class .square of course.

const elements = document.querySelectorAll(".square");

anime({
    targets: elements,
    translateX: 250
})

Alone this functionality makes it easy for us to use Anime.js with React together, because it allows us to pass in a reference.

As example we could use a Toggle Button, here an example with React Hooks:

As you can see, all we have to do is to create a reference to the JSX Element we are going to animate. We then pass the Reference as target into the anime config when we call it.

const handleToggle = () => {
    anime({
        targets: toggleRef.current,
        translateX: 0
    })
}

That's it, it's simple as that and we can make use of this fantastic library within our React applications.