Framer motion: do animation while transition occurs?

Viewed 26

I'm using simple transition effect for a toggle button, very similar to the docs, my Handle is like this:

    <Handle
      animate
      layout
      isOn={isOn}
      transition={spring}
      variantColor={variantColor}
      onClick={() => setIsOn(!isOn)}
    />

My Handle styling:

const Handle = styled(motion.div)<{ isOn: boolean; variantColor: string }>(
  ({ isOn, theme, variantColor }) => ({
    width: theme.spacing(3),
    height: theme.spacing(3),
    position: 'absolute',
    left: isOn ? '65%' : '0%',
    backgroundColor: variantColor,
    borderRadius: 'inherit',
    cursor: 'pointer',
  }),
);

The left propoerty transitions when clicking, so it toggles between '65%' to '0%'. What I would like to do is also add a scaling animation, one that makes the Handle larger and then going back to its original size, at the same time while the left transition takes effect. So if I try:

<Handle
  animate={{
    scale: [null, 1.2, 1],
    opacity: 1,
  }}
  layout
  isOn={isOn}
  transition={spring}
  variantColor={variantColor}
  onClick={() => setIsOn(!isOn)}
/>

The scaling animation occurs when the page loads, how can I have this animation trigger when transition occurs? Please note that the scaling animation doesn't care whether isOn is true or false as opposed to the transition that moves the Handle from left to right and vice versa. The scaling animation is exactly the same and should just occurs alongside the left transition.

1 Answers

I found out that one way to do it would be to use the useAnimation hook from framer motion library.

import { motion, useAnimation } from 'framer-motion';

const control = useAnimation();

Then use it inside onClick event:

      onClick={() => {
        setIsOn(!isOn);
        control.start({
          scale: [null, 1.1, 1],
          transition: { duration: 0.2 },
        });
      }}
Related