Some Examples » 25. Colors: Switching between states
25. Colors: Switching between states
Here the onHoverStart()
and onHoverEnd()
events flip an isHover
state. This state, in turn, animates the box’s size and rotation and 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 I share the state between them with createStore
.
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 })}
/>
)
}
}