profile
Tuan Phung
Articles
Snippets
August 17, 2022
Updated on September 22, 2022
How to make Confetti with React in 5 minutes 🎉
How to make confetti effect with react-canvas-confetti package in React.
Confettiiii

Everyone loves confetti, right? 😄 Today, I’m going to show you how to add the confetti effect to your React app just in 5 minutes. I already made the components so feel free to copy them to your project.

Video Demo

Here is a video of what we will be building today.

Confetti secret sauce

First of all, we need to install the library react-canvas-confetti. This is an example of the realistic confetti effect. They have more examples in their storybook

javascript
import { useCallback, useEffect, useRef } from 'react';
import ReactCanvasConfetti from 'react-canvas-confetti';
export default function Confetti() {
const refAnimationInstance = useRef(null);
const getInstance = useCallback(instance => {
refAnimationInstance.current = instance;
}, []);
const makeShot = useCallback((particleRatio, opts) => {
refAnimationInstance.current &&
refAnimationInstance.current({
...opts,
origin: { y: 0.7 },
particleCount: Math.floor(200 * particleRatio)
});
}, []);
useEffect(() => fire(), []);
const fire = useCallback(() => {
makeShot(0.25, {
spread: 26,
startVelocity: 55
});
makeShot(0.2, {
spread: 60
});
makeShot(0.35, {
spread: 100,
decay: 0.91,
scalar: 0.8
});
makeShot(0.1, {
spread: 120,
startVelocity: 25,
decay: 0.92,
scalar: 1.2
});
makeShot(0.1, {
spread: 120,
startVelocity: 45
});
}, [makeShot]);
return (
<ReactCanvasConfetti
refConfetti={getInstance}
style={{
position: 'fixed',
pointerEvents: 'none',
width: '100%',
height: '100%',
top: 0,
left: 0
}}
/>
);
}

Use it in a component

The usage of the Confetti component is quite straight forward, just use the confetti component in the codebase 🎉

javascript
import { useState } from 'react';
import Confetti from './Confetti';
export default function ConfettiLayout() {
const [isVisible, setIsVisible] = useState(false);
return (
<>
<button onClick={() => setIsVisible(true)}>Fire</button>
{isVisible && <Confetti />}
</>
);
}
Latest blog
More blog
;