How to animate width and height with framer motion

using both the animate property and the animate/useMotionValue combo

Option 1: Using the animate prop

This is the preferred way of using framer-motion; declaratively and in response to state changes

1
2const AnimateWithAnimateProp = () => {
3 const [isBig, setIsBig] = useState(false);
4
5 return (
6 <Root>
7 <Container>
8 <MotionBox
9 // setting initial to false starts the animation at the first value in animate
10 initial={false}
11 // using our state to toggle through values that we want
12 animate={{
13 height: isBig ? 150 : 100,
14 width: isBig ? 150 : 100
15 }}
16 />
17 </Container>
18 <Button onClick={() => setIsBig((value) => !value)}>
19 {isBig ? "make it small" : "make it big"}
20 </Button>
21 <Branding />
22 </Root>
23 );
24};
25

Option 2: Using the animate helper and useMotionValue hook

This method allows more imperative control to start and stop the animation as state changes

1
2const AnimateWithAnimateFunction = () => {
3 const [isBig, setIsBig] = useState(false);
4 const size = useMotionValue(100);
5
6 useEffect(() => {
7 const to = isBig ? 150 : 100;
8 const controls = animate(size, to, {
9 // ...otherProps
10 });
11 return controls.stop;
12 }, [isBig]);
13
14 return (
15 <Root>
16 <Container>
17 <MotionBox
18 initial={false}
19 animate={{
20 height: isBig ? 150 : 100,
21 width: isBig ? 150 : 100
22 }}
23 />
24 </Container>
25 <Button onClick={() => setIsBig((value) => !value)}>
26 {isBig ? "make it small" : "make it big"}
27 </Button>
28 <Branding />
29 </Root>
30 );
31};
32

Glad you found this snippet!

subscribe to my blog for more josh content right in your inbox

Contact me at

my reddit accountmy codepen accountmy twitter accountmy github account