Skip to example

AnimateView: Toggle

An example of using AnimateView to animate a toggle switch with smooth update animations using Motion for React.

React

Source code

"use client"

import { spring } from "motion"
import { AnimateView } from "motion/react-animate-view"
import { startTransition, useState } from "react"

/**
 * Title: AnimateView: Toggle
 */

export default function Toggle() {
    const [isOn, setIsOn] = useState(false)

    return (
        <div className="toggle-example">
            <AnimateView
                transition={{
                    type: spring,
                    visualDuration: 0.2,
                    bounce: 0.2,
                }}
            >
                <button
                    className="toggle-container"
                    style={{
                        justifyContent: isOn ? "flex-end" : "flex-start",
                        backgroundColor: isOn
                            ? "var(--hue-6)"
                            : "rgba(255, 255, 255, 0.15)",
                    }}
                    onClick={() =>
                        startTransition(() => setIsOn(!isOn))
                    }
                >
                    <Handle />
                </button>
            </AnimateView>
            <StyleSheet />
        </div>
    )
}

function Handle() {
    return (
        <AnimateView
            transition={{
                type: spring,
                visualDuration: 0.2,
                bounce: 0.2,
            }}
        >
            <div className="toggle-handle" />
        </AnimateView>
    )
}

/** ==============   Styles   ================ */

function StyleSheet() {
    return (
        <style>{`
            .toggle-example {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 100%;
            }

            .toggle-container {
                width: 100px;
                height: 50px;
                border-radius: 50px;
                cursor: pointer;
                display: flex;
                padding: 10px;
                border: none;
            }

            .toggle-handle {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background-color: white;
            }
        `}</style>
    )
}