React hook for highly-performant and manipulable animations using Web Animations API.
React hook for highly-performant and manipulable animations using Web Animations API.
Using Web Animations API (a.k.a WAAPI) in the React hook way. Let's create highly-performant, flexible and manipulable web animations in the modern world. Hope you guys it!
❤️ it? ⭐️ it on GitHub or Tweet about it.
⚡️ Try yourself: https://use-web-animations.netlify.app
⚡️ Try yourself: https://use-web-animations.netlify.app#animations
refs for some reasons.react.To use use-web-animations, you must use [email protected] or greater which includes hooks.
This package is distributed via npm.
$ yarn add @wellyshen/use-web-animations
# or
$ npm install --save @wellyshen/use-web-animationsWith the Web Animations API, we can move interactive animations from stylesheets to JavaScript, separating presentation from behavior. The API was designed based on the concept of the CSS Animations but there're still some differences between them. I strongly recommend you to read the documentation before we dive into this hook.
The API design of the hook not only inherits the DX of the Web Animations API but also provides useful features and sugar events to us. Here are some examples to show you how does it work.
⚠️ Most modern browsers support Web Animations API natively. You can also use polyfill for full browser support.
Create an animation by the keyframes and animationOptions options (these are the parameters of the Element.animate()).
This hook supports the pseudoElement property via the
animationOptionsoption.
…For browsers that don't yet support the onReady and onFinish events, we can use the onUpdate to monitor the animation's state instead.
let prevPending = true;
const App = () => {
const { ref } = useWebAnimations({
// ...
onUpdate: ({ playState, animation: { pending } }) => {
if (prevPending && !pending) {
console.log("Animation is ready to play");
}
prevPending = pending;
if (playState === "finished") {
console.log("Animation has finished playing");
}
},
});
// ...
};The keyframes and animationOptions are cached when the hook is mounted. However, we can set/update the animation by the animation method.
const { animation } = useWebAnimations();
const changeAnim = () =>
animation({
keyframes: { transform: ["translateX(0)", "translateX(100px)"] },
animationOptions: 1000,
id: "123",
playbackRate: 1,
autoPlay: true,
});The shortcoming with existing technologies was the lack of playback control. The Web Animations API provides several useful methods for controlling playback: play, pause, reverse, cancel, finish, seek, control speed via the methods of the Animation interface. This hook exposes the animation instance for us to interact with animations, we can access it by the getAnimation() return value.
…When using the Web Animations API, we can get the information of an animation via the properties of the Animation interface. However, we can get the information of an animation by the getAnimation() return value as well.
import useWebAnimations from "@wellyshen/use-web-animations";
const App = () => {
const { ref, getAnimation } = useWebAnimations({
keyframes: { transform: "translateX(500px)" },
animationOptions: { duration: 1000, fill: "forwards" },
});
const speedUp = () => {
const animation = getAnimation();
animation.updatePlaybackRate(animation.playbackRate * 0.25);
};
const jumpToHalf = () => {
const animation = getAnimation();
animation.currentTime = animation.effect.getTiming().duration / 2;
};
return (
);
};The animation instance isn't a part of React state, which means we need to access it by the getAnimation() whenever we need. If you want to monitor an animation's information, here's the onUpdate event for you. The event is implemented by the requestAnimationFrame internally and the event callback is triggered when the animation enters running state or changes state.
import { useState } from "react";
import useWebAnimations from "@wellyshen/use-web-animations";
const App = () => {
const [showEl, setShowEl] = useState(false);
const { ref } = useWebAnimations({
keyframes: { transform: "translateX(500px)" },
animationOptions: { duration: 1000, fill: "forwards" },
onUpdate: ({ animation }) => {
if (animation.currentTime > animation.effect.getTiming().duration / 2)
setShowEl(true);
},
});
return (
);
};We can create and play an animation at the animationOptions we want by the animate method, which is implemented based on the Element.animate(). It's useful for interactions and the composite modes.
Let's create a mouse interaction effect:
import { useEffect } from "react";
import useWebAnimations from "@wellyshen/use-web-animations";
const App = () => {
const { ref, animate } = useWebAnimations();
useEffect(() => {
document.addEventListener("mousemove", (e) => {
// The target will follow the mouse cursor
animate({
keyframes: { transform: `translate(${e.clientX}px, ${e.clientY}px)` },
animationOptions: { duration: 500, fill: "forwards" },
});
});
}, [animate]);
return (
);
};Create a bounce effect via lifecycle and composite mode:
…⚠️ Composite modes isn't fully supported by all the browsers, please check the browser compatibility carefully before using it.
Too lazy to think about animation? We provide a collection of ready-to-use animations for you, they are implemented based on Animate.css.
import useWebAnimations, { bounce } from "@wellyshen/use-web-animations";
const App = () => {
// Add a pre-defined effect to the target
const { ref } = useWebAnimations({ ...bounce });
return (
);
};We can customize the built-in animation by overriding its properties:
const { keyframes, animationOptions } = bounce;
const { ref } = useWebAnimations({
keyframes,
animationOptions: {
...animationOptions,
delay: 1000, // Delay 1s
duration: animationOptions.duration * 0.75, // Speed up the animation
},
});See all available animations
refIn case of you had a ref already or you want to share a ref for other purposes. You can pass in the ref instead of using the one provided by this hook.
const ref = useRef();
const { playState } = useWebAnimations({ ref });This hook supports TypeScript, you can tell the hook what type of element you are going to animate through the generic type:
const App = () => {
const { ref } = useWebAnimations();
return ;
};For more available types, please check it out.
const returnObj = useWebAnimations(options?: object);It's returned with the following properties.
| Key | Type | Default | Description |
|---|---|---|---|
ref |
object | Used to set the target element for animating. |
No open issues yet, or sync has not completed.