Hooks To Leverage The Web Animations API

React hooks that provide an API to use the Web Animations API.

How to use it:

1. Install and import the useWebAnimation.

import { useState } from "react";
import { useWebAnimation } from "use-web-animation";

2. This example shows how to animate an element with various trigger events.

export default function App() {
  const [hovering, setHovering] = useState();
  const [opacityRef] = useWebAnimation({
    from: 0,
    to: 100,
    property: "opacity",
    getValue: (x) => `${x}%`,
    duration: 333
  });
  const [transformRef] = useWebAnimation({
    from: 0.5,
    to: 1,
    property: "transform",
    getValue: (x) => `scale(${x})`,
    duration: 333
  });
  const [hoverRef, hover] = useWebAnimation({
    from: hovering ? 1.2 : 1,
    to: hovering ? 1 : 1.2,
    property: "transform",
    getValue: (x) => `scale(${x})`,
    pause: true,
    duration: 333
  });
  const [clickRef, click] = useWebAnimation({
    from: hovering ? 1.2 : 1,
    to: 0.8,
    property: "transform",
    getValue: (x) => `scale(${x})`,
    pause: true,
    duration: 333
  });
  const [reverseClickRef, reverseClick] = useWebAnimation({
    from: 0.8,
    to: 1.2,
    property: "transform",
    getValue: (x) => `scale(${x})`,
    pause: true,
    duration: 333
  });
  return (
    <div
      ref={(x) => {
        transformRef.current = opacityRef.current = clickRef.current = reverseClickRef.current = hoverRef.current = x;
      }}
      className="box"
      onMouseOver={() => {
        setHovering(true);
        hover();
      }}
      onMouseOut={() => {
        setHovering(false);
        hover();
      }}
      onClick={() => {
        click(reverseClick);
      }}
    />
  );
}

3. Available props.

duration?: number;
infinite?: boolean;
pause?: boolean;
delay?: number;
easing?: string;
from: number;
to: number;
getValue: (x: number) => string;
property: string;

Preview:

Hooks To Leverage The Web Animations API

Download Details:

Author: JoviDeCroock

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/JoviDeCroock/use-web-animation

License: MIT

You Might Be Interested In:

Tags:

Add Comment