Skip to main content
Version: 5.x

withLoop

The withLoop modifier allows you to repeat (loop) an animation a specified number of times or indefinitely. You wrap an existing animation descriptor with withLoop, and it will restart automatically based on the configured options.

Syntax

withLoop(animation,iterations?, options?) => Descriptor

Parameters

  • animation: The animation descriptor you want to repeat (eg: (withSpring, withTiming, withDecay, etc.) ).
  • iterations (optional) : A number specifying how many times the animation should run.
    • If omitted or set to -1, the animation will loop indefinitely.
    • Default: -1 (Infinity).
  • options (object, optional): An object to configure the loop's behavior.
OptionsDescrptionsTypeDefault
onStartA callback function invoked when the animation begins.function()-
onCompleteA callback function invoked when the animation finishes.function()-

Example

This example demonstrates how to repeat a sequence of animations multiple times using the powerful withLoop utility. This is exactly what you need when you want looping behaviors, like bouncing, oscillating, or infinite motion.

import React from 'react';
import {
  useValue,
  animate,
  withTiming,
  withSequence,
  withSpring,
  withDelay,
  withDecay,
  withLoop,
} from 'react-ui-animate';

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

  return (
    <>
      <button
        onClick={() =>
          setObj(
            withLoop(
              withSequence([
                withTiming({ x: 100 }),
                withTiming({ y: 100 }),
                withTiming({ x: 0 }),
                withTiming({ y: 0 }),
              ]),
              5,
              {
                onStart() {
                  console.log('Loop started');
                },
                onComplete() {
                  console.log('Loop completed');
                },
              }
            )
          )
        }
      >
        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,
        }}
      />
    </>
  );
}

What’s Happening Here:

  1. A simple box starts at position (0, 0) with width 100.
  2. On clicking Start:
    • A sequence begins that:
      • Moves horizontally to x: 100 → right.
      • Moves vertically to y: 100 → down.
      • Moves back horizontally to x: 0 → left.
      • Moves back vertically to y: 0 → up.
  3. This sequence loops 5 times continuously.