Celebrate Your Success with a Confetti Cannon!

Who doesn’t love a good celebration? A pat on the back, a shout-out, or a festive confetti explosion can make all the difference in our daily lives. In this tutorial, we’ll show you how to create a confetti cannon that fires off any element using React Spring from scratch. No prior React Spring experience needed! Just a basic understanding of React and hooks will do.

Breaking Down the Project

When tackling a new project, it’s essential to break it down into manageable phases. Here’s our game plan:

  • Get Something on the Page: Create a simple to-do app that fires confetti when you complete an item.
  • Set Up React Spring: Learn how to set up React Spring and create a basic confetti dot.
  • Write Pseudo-Physics Helpers: Make the confetti dot move like it’s being fired from a cannon.
  • Anchoring the Confetti: Align the confetti animation with a specific element.
  • Creating the Confetti Cannon: Make the confetti cannon spray a randomized fan of confetti.
  • Polishing the Experience: Add fade-out, randomize colors, shapes, and sizes for a more realistic effect.

Let’s Get Started!

1. Something on the Page

Create a simple to-do app that fires confetti when you complete an item. Add a single confetti dot and play with it for the next few steps.

import React, { useState } from 'eact';

function TodoApp() {
  const [tasks, setTasks] = useState([
    { id: 1, text: 'Task 1', completed: false },
    { id: 2, text: 'Task 2', completed: false },
  ]);

  const handleCompleteTask = (id) => {
    setTasks((prevTasks) => prevTasks.map((task) => (task.id === id? {...task, completed: true } : task)));
  };

  return (
{tasks.map((task) => (

handleCompleteTask(task.id)} />
{task.text}

))}


  );
}

export default TodoApp;

2. React Spring Setup

React Spring is the animation library we’ll be using. It’s unique in that it uses springs rather than keyframes to create natural-looking animations. Set up React Spring with our confetti dot by installing react-spring and adding the necessary imports.

npm install react-spring
import { useSpring, animated } from 'eact-spring';

function ConfettiDot() {
  const { x, y } = useSpring({
    x: 0,
    y: 0,
  });

  return (
    
      🎉
    
  );
}

export default ConfettiDot;

3. Pseudo-Physics

Make the confetti dot move like it’s being fired from a cannon. We’ll use React Spring to simulate the confetti’s velocity at time t. Create a spring that goes from 100 to 0, representing pixels per second.

const velocitySpring = useSpring({
  velocity: 100,
  config: { mass: 1, tension: 500, friction: 20 },
});

const [x, y] = useSpring({
  x: 0,
  y: 0,
  velocity: velocitySpring.velocity,
});

4. Anchoring

Align the confetti animation with a specific element. Use refs to attach the animation to the checkbox and calculate the middle of the ref element.

const checkboxRef = React.createRef();

const checkboxMiddleX = checkboxRef.current.offsetLeft + checkboxRef.current.offsetWidth / 2;
const checkboxMiddleY = checkboxRef.current.offsetTop + checkboxRef.current.offsetHeight / 2;

const [x, y] = useSpring({
  x: checkboxMiddleX,
  y: checkboxMiddleY,
});

5. Creating the Confetti Cannon

Make the confetti cannon spray a randomized fan of confetti. Randomize the initial horizontal and upward velocity of each dot, and add vertical and horizontal ranges.

const confettiDots = Array(20).fill(0).map(() => ({
  x: Math.random() * 100 - 50,
  y: Math.random() * 100 - 50,
  velocityX: Math.random() * 5 - 2.5,
  velocityY: Math.random() * 5 - 2.5,
}));

const [x, y] = useSpring({
  x: confettiDots.map((dot) => dot.x),
  y: confettiDots.map((dot) => dot.y),
});

6. Polishing the Experience

Add fade-out, randomize colors, shapes, and sizes for a more realistic effect. Make the confetti disappear as it falls, and add some variety to the shapes and colors.

const confettiDots = Array(20).fill(0).map(() => ({
  x: Math.random() * 100 - 50,
  y: Math.random() * 100 - 50,
  velocityX: Math.random() * 5 - 2.5,
  velocityY: Math.random() * 5 - 2.5,
  color: `#${Math.floor(Math.random() * 16777215).toString(16)}`,
  shape: Math.random() > 0.5? '🎉' : '🎊',
  size: Math.random() * 2 + 1,
}));

const [x, y, opacity] = useSpring({
  x: confettiDots.map((dot) => dot.x),
  y: confettiDots.map((dot) => dot.y),
  opacity: 1,
  config: { duration: 2000 },
  onRest: () => {
    opacity.setValue(0);
  },
});

Congratulations! You’ve created a confetti cannon from scratch using React and React Spring. Now you should be more familiar with using React Spring’s useSpring hook to create powerful and performant animations. Get creative and make your own branded confetti cannons!

Leave a Reply