Animation » Example Animations » 25. Colors: Switching between states

25. Colors: Switching between states

Here the onHoverStart() and an onHoverEnd() event change an isHover state, which in turn changes the box’s size and rotation plus the background color.

Code component

export default function CC_25_Colors_Switching_between_states(props) {
    const [isHover, setHover] = useState(false)

    return (
        <motion.div
            style={{
                width: 400,
                height: 400,
                ...props.style,
                display: "flex",
                placeItems: "center",
                placeContent: "center",
            }}
            animate={{ backgroundColor: isHover ? "#60f" : "#20a5f6" }}
            transition={{ duration: 0.5 }}
        >
            <motion.div
                style={{
                    width: 150,
                    height: 150,
                    borderRadius: 30,
                    backgroundColor: "#fff",
                }}
                animate={{
                    scale: isHover ? 0.8 : 1,
                    rotate: isHover ? 90 : 0,
                }}
                onHoverStart={() => setHover(true)}
                onHoverEnd={() => setHover(false)}
            />
        </motion.div>
    )
}

Code overrides

Here we have two overrides, so the state is shared between them with a createStore object.

const useStore = createStore({ isHover: false })

export function Background(Component): ComponentType {
    return (props) => {
        const [store, setStore] = useStore()

        return (
            <Component
                {...props}
                animate={{
                    backgroundColor: store.isHover ? "#60f" : "#20a5f6",
                }}
                transition={{ duration: 0.5 }}
            />
        )
    }
}

export function Colors_Switching_between_states(Component): ComponentType {
    return (props) => {
        const [store, setStore] = useStore()

        return (
            <Component
                {...props}
                animate={{
                    scale: store.isHover ? 0.8 : 1,
                    rotate: store.isHover ? 90 : 0,
                }}
                onHoverStart={() => setStore({ isHover: true })}
                onHoverEnd={() => setStore({ isHover: false })}
            />
        )
    }
}

Leave a Reply