Motion+

Multi state badge

A badge that can be in multiple states, such as processing, success, or error.

React
Tutorial time
5 min
Difficulty

Tutorial

Introduction

The Multi-state Badge example shows how to create a component that smoothly animates between different states. This pattern is commonly used in UIs to provide visual feedback during form submissions, network requests, or any process with multiple stages.

In this tutorial, we'll learn to use:

  • motion components for creating animatable elements
  • AnimatePresence for coordinating the entrance and exit of components
  • The animate function for triggering imperative animations
  • useTime and useTransform motion value hooks for creating continuous animations

Using Motion for these animations offers significant advantages over standard CSS transitions. Motion handles the complex orchestration of multiple elements entering and exiting simultaneously, manages element measurement for dynamic content, and provides a declarative API for SVG path animations that would otherwise require complex JavaScript.

Get started

First, let's create the basic structure of our multi-state badge:

"use client"

import { useState } from "react"

export default function MultiStateBadge() {
    const [badgeState, setBadgeState] = useState("idle")

    return (
        <div style={styles.container}>
            <button
                onClick={() => {
                    setBadgeState(getNextState(badgeState))
                }}
            >
                <div style={styles.badge}>Badge</div>
            </button>
        </div>
    )
}

const styles = {
    container: {
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        alignItems: "center",
        padding: 16,
        height: 80,
    },
    badge: {
        backgroundColor: "#FFFFFF",
        color: "#000000",
        display: "flex",
        overflow: "hidden",
        alignItems: "center",
        justifyContent: "center",
        padding: "12px 20px",
        borderRadius: 999,
    },
}

const STATES = {
    idle: "Start",
    processing: "Processing",
    success: "Done",
    error: "Something went wrong",
} as const

const getNextState = (state) => {
    const states = Object.keys(STATES)
    const nextIndex = (states.indexOf(state) + 1) % states.length
    return states[nextIndex]
}

This gives us a simple button with a badge that cycles through different states when clicked. When we press the button, the getNextState function determines which state comes next in our cycle and updates the state accordingly.

Related examples

Latest in React

Motion+

Unlock all 400+ examples

  • Source code for every Plus example.
  • Provide examples direct to your agent via Motion's MCP.
  • Lifetime access to new examples and APIs.