Search

The Initial Property

The Initial Property

Another property, initial, lets you decide which values a Motion component should animate from.

Setting the value(s) to animate from

Let’s say you would like an element to fade in when it appears, so initially, it should have an opacity of 0. Without changing its opacity using style or with a CSS class, you can use initial to set the opacity the element should animate from.

export function Example() {
    return (
        <motion.div
            style={{
                width: 150,
                height: 150,
                borderRadius: 30,
                backgroundColor: "#fff"
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1, transition: { duration: 1 } }}
            whileHover={{ scale: 1.05, boxShadow: "0px 5px 8px #207" }}
        />
    );
}
The initial property

(Hit to see that fade-in animation again.)

open in CodeSandbox

initial

Canceling an initial animation

One more thing about initial: Setting it to false will cancel the initial animate animation.

Say you have an element that changes to a random color every time you tap it, and it also appears with a random color. You can cancel that initial animation (from white to the first color) by setting initial to false.

export function Example() {
    const [color, setColor] = useState(
        `hsl(${Math.floor(Math.random() * 360)},80%,50%)`
    );

    function changeColor() {
        setColor(`hsl(${Math.floor(Math.random() * 360)},80%,50%)`);
    }

    return (
        <motion.div
            style={{
                width: 150,
                height: 150,
                borderRadius: 30,
                backgroundColor: "#fff",
            }}
            initial={false}
            animate={{ backgroundColor: color }}
            onTap={changeColor}
            transition={{ duration: 0.5 }}
        />
    );
}
The initial property – Initial: false
open in CodeSandbox

(I’m using HSL colors, changing Hue to a random number between 0 and 360. Saturation and Lightness always stay the same.)

Naturally, when you comment out the initial: false, it will animate :

export function Example() {
    const [color, setColor] = useState(
        `hsl(${Math.floor(Math.random() * 360)},80%,50%)`
    );

    function changeColor() {
        setColor(`hsl(${Math.floor(Math.random() * 360)},80%,50%)`);
    }

    return (
        <motion.div
            style={{
                width: 150,
                height: 150,
                borderRadius: 30,
                backgroundColor: "#fff",
            }}
            // initial={false}
            animate={{ backgroundColor: color }}
            onTap={changeColor}
            transition={{ duration: 0.5 }}
        />
    );
}

initial

Leave a Reply

Scroll to Top