DEV Community 👩‍💻👨‍💻

Sharath Prabhal
Sharath Prabhal

Posted on

Building a bubble heart counter in React using Framer Motion

I started off wanting to write an extensive step-by-step tutorial on how to build a bubble heart counter. But, Framer Motion turned out to be so simple that I decided to just post my code below. Hit me up @SharathPrabhal if you have any questions or want me to write a post on other animations patterns.

function HeartComponent() {
  const [floatingHearts, setFloatingHearts] = useState<JSX.Element[]>([]);
  return (
    <motion.div
      className="relative rounded-full text-5xl inline-block p-2 cursor-pointer"
      onClick={() => {
        setFloatingHearts([
          ...floatingHearts,
          <motion.div
            key={floatingHearts.length}
            className="absolute top-0 z-50"
            animate={{
              y: -150,
              opacity: 0,
              scale: 1.75,
              x: [0, randomNumber(-150, 150)],
            }}
            transition={{ duration: 2 }}
          >
            <HeartFilledIcon
              style={{
                color: randomColor({
                  luminosity: 'bright',
                }),
              }}
            />
          </motion.div>,
        ]);
      }}
    >
      <HeartIcon />
      {floatingHearts}
    </motion.div>
  );
}

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs