Skip to content

Confetti cannon

confetti cannon

With my new course launching, I wanted to make a little quiz on the landing page. The quiz is short (4 questions), but they're non-trivial. It's a true/false format, so quick to complete.

When the user completes the quiz, they're shown their score, which they can then Tweet. The goal being to give a little delight to the user with some small gamification, and to draw folks in from Twitter (get that funnel going).

To add a lil extra pizazz, I wanted to add the ever ubiquitous confetti cannon. I use a confetti cannon for my own personal pomodoro/todo-list/whatever thing I built for myself - and I always enjoy it (I also use a marquee tag in that app :chefs_kiss:). In fact, I almost expect confetti it in certain situations these days.

My personal productivity app

To add a confetti cannon in a React (or literally any kind of app), it's fairly straight-forward. The library I went with with is react-dom-confetti and it's a breeze to setup (I normally stay away from calling things "simple", but this really is).

1. Add it to your project

yarn add react-dom-confetti

OR

npm install react-dom-confetti

2. Import it in your component

import Confetti from "react-dom-confetti";

3. Add the Confetti configuration

// stole this from the example in the package's README
// play around with it as you wish
const confettiConfig = {
  angle: 90,
  spread: 360,
  startVelocity: 30,
  elementCount: 70,
  dragFriction: 0.12,
  duration: 3000,
  stagger: 3,
  width: "10px",
  height: "10px",
  perspective: "500px",
  // I had some CSS variables set for my color theme
  colors: [
    "var(--pink)",
    "var(--teal)",
    "var(--blue)",
    "var(--purple)",
    "var(--white)",
  ],
};

4. Use the Confetti component

const ConfettiButton = () => {
  const [showConfetti, setShowConfetti] = useState(false);

  return (
    <>
      <Confetti
        className="confetti-cannon"
        active={showConfetti}
        config={confettiConfig}
      />
      <button onClick={() => setShowConfetti(true)}>Click me!</button>
    </>
  );
};

5. Set prefers-reduced-motion

Not everyone wants or responds well to all this motion. It can make some people feel physically sick, while some other folks just prefer not to experience all the animations developers are throwing into sites and apps. It's best to honor what your user wants/needs, they'll appreciate it!

To just plain disable the whole confetti cannon for users that prefer reduced motion, we can use a CSS media query that checks the user's operating system or browser. Read more over at MDN.

@media (prefers-reduced-motion) {
  .confetti-cannon {
    display: none;
  }
}

All done 🎉

Wanna get better at working with arrays in JS? Check out my course 🔥