Notion Blog Starter
August 17, 2022
Updated on October 13, 2022
How to make Confetti with React in 5 minutes ๐ŸŽ‰
How to make confetti effect with react-canvas-confetti package in React.
article cover
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

typescript
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 />}
</>
);
}
Subscribe to the newsletter
Get emails from me about web development, tech, and early access to new articles.
Be the first to know when the blog is published
;