Skip to content

Confetti Cannon

JavaScript1 min read

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

1yarn add react-dom-confetti

OR

1npm install react-dom-confetti

2. Import it in your component

1import Confetti from "react-dom-confetti";

3. Add the Confetti configuration

1// stole this from the example in the package's README
2// play around with it as you wish
3const confettiConfig = {
4 angle: 90,
5 spread: 360,
6 startVelocity: 30,
7 elementCount: 70,
8 dragFriction: 0.12,
9 duration: 3000,
10 stagger: 3,
11 width: "10px",
12 height: "10px",
13 perspective: "500px",
14 // I had some CSS variables set for my color theme
15 colors: [
16 "var(--pink)",
17 "var(--teal)",
18 "var(--blue)",
19 "var(--purple)",
20 "var(--white)",
21 ],
22};

4. Use the Confetti component

1const ConfettiButton = () => {
2 const [showConfetti, setShowConfetti] = useState(false);
3
4 return (
5 <>
6 <Confetti
7 className="confetti-cannon"
8 active={showConfetti}
9 config={confettiConfig}
10 />
11 <button onClick={() => setShowConfetti(true)}>Click me!</button>
12 </>
13 );
14};

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.

1@media (prefers-reduced-motion) {
2 .confetti-cannon {
3 display: none;
4 }
5}

All done 🎉

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

© 2021 by Jonathan Speek