Skip to main content
Version: 5.x

withSpring

The withSpring modifier animates a value using spring physics, creating natural motion with realistic bounce and overshoot effects.

Syntax

withSpring(toValue, options?) => Descriptor

Parameters

  • toValue: The target value for the animation. This can be a number, string, object, or array.
  • Options (optional): An object to configure the spring animation.
OptionsDescrptionsTypeDefault
stiffnessDetermines the spring's stiffness, affecting its resistance to displacement.number158
dampingControls the damping ratio, influencing how quickly the spring loses energy.number20
massRepresents the mass of the spring, affecting its inertia.number1
onStartA callback function invoked when the animation begins.function()-
onChangeA callback function invoked on every frame of the animation, providing the current value.function()-
onCompleteA callback function invoked when the animation finishes.function()-

Example: Animating Multiple Values with useValue + withSpring

This example shows how to animate multiple numeric properties together using useValue, withSpring, and animate components.

import React from 'react';
import { useValue, withSpring, animate } from 'react-ui-animate';

export default function App() {
  const [obj, setObj] = useValue({ x: 0, y: 0, width: 100, height: 100 });

  return (
    <>
      <button
        onClick={() =>
          setObj(
            withSpring(
              { x: 100, y: 100, width: 200, height: 200 },
              {
                onStart: () => console.log('START'),
                onComplete: () => console.log('Animation complete'),
              }
            )
          )
        }
      >
        Start
      </button>
      <button onClick={() => setObj({ x: 0, y: 0, width: 100, height: 100 })}>
        Reset
      </button>

      <animate.div
        style={{
          width: obj.width,
          height: 100,
          backgroundColor: 'teal',
          left: 0,
          top: 0,
          translateX: obj.x,
          translateY: obj.y,
          borderRadius: 4,
        }}
      />
    </>
  );
}

Key Highlights:

  • useValue manages multiple animated values as an object (x, y, width, height).
  • withSpring smoothly animates the values with a spring physics-based transition.
  • You can attach callbacks like onStart and onComplete to the animation lifecycle.
  • The <animate.div> component directly binds the animated values to styles for rendering.

How it Works:

  1. Initially, the box starts at position (0, 0) with width & height 100.
  2. Clicking Start triggers an animation to:
    • Move to (x: 100, y: 100)
    • Resize to width: 200, height: 200
  3. Once complete, it logs "Animation complete".
  4. Clicking Reset snaps it back to the initial state without animation.