Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page.

However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas for the confetti is correctly set for all elements (verified with a background-color).

https://i.stack.imgur.com/SI082.png

So here's my logic:

In my ParentComponent, I iterate over players and create cards for each player. The dimensions of the card are calculated as follows:

const updateCardDimensions = () => {
    if (cardRef.current) {
      const rect = cardRef.current.getBoundingClientRect();
      setCardDimensions({ width: rect.width, height: rect.height });
    }
  };

  useEffect(() => {
    // Initial update
    updateCardDimensions();

    // Attach the resize event listener
    window.addEventListener('resize', updateCardDimensions);

    // Clean up the event listener
    return () => {
      window.removeEventListener('resize', updateCardDimensions);
    };
  }, [cardRef]);

I then iterate over players to create cards for each player.

{gameData.players.map((player) => {
              return (
                <PlayerCardWithConfetti
                  key={player.id}
                  player={player}
                  cardDimensions={cardDimensions}
                  winners={winners}
                  cardRef={cardRef}
                  .. (removed unnecessary props)
                />
              );
            })}

Within the PlayerCardWithConfetti component, I use the react-confetti library to generate a confetti effect for winning cards. I also set a backgroundColor to confirm correct canvas setup for the confetti effect (which is fine).

<div key={player.id} className="col-md-4 mb-3">
      <div style={{ position: 'relative' }}>
        {isPlayerWinner(player.id) && (
          <Confetti
            style={{backgroundColor: 'blanchedalmond'}}
            width={cardDimensions.width}
            height={cardDimensions.height}
            recycle={true}
            key={`confetti-${player.id}`}
          />
        )}
        <PlayerCard
          player={player}
          isWinner={winners.some((winner) => winner.id === player.id)}
          cardRef={cardRef}
          .. (removed unnecessary props)
        />
      </div>
    </div>

My expectation was to see a confetti effect for each qualifying card, given that the canvases were properly configured. However, the confetti effect only appears on the last card:

https://i.stack.imgur.com/SI082.png

I suspected that the loop might be causing the issue, so I manually recreated the cards but still encountered the same problem – confetti only visible on the last card:

 <PlayerCardWithConfetti
              key={Math.random()}
              player={gameData.players[0]}
              cardDimensions={cardDimensions}
              winners={winners}
              cardRef={cardRef}
              .. (removed unnecessary props)
            />
            <PlayerCardWithConfetti
              key={Math.random()}
              player={gameData.players[1]}
              cardDimensions={cardDimensions}
              winners={winners}
              cardRef={cardRef}
              .. (removed unnecessary props)
            />

As a test, I utilized two isolated instances of the react-confetti effect unrelated to my components. This experiment successfully displayed one effect at the bottom left corner and another at the bottom right corner without any issues. This leads me to suspect a potential rendering or React-related factor?

If anyone familiar with the react-confetti library can provide insight or assistance, I would greatly appreciate it as I've been grappling with this challenge for the past two days.

Thank you!

Answer №1

My method for addressing this issue involves passing the canvas reference to the Confetti component. Here's an example of how I do it:

export function MyConfetti(){
   const confettiRef = useRef<HTMLCanvasElement>(null)
   return (<Confetti ref={confettiRef}/>)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the benefits of adding member functions to the data structures of React.js store?

Using React.js and Typescript, I store plain Javascript objects in the React.js store. These objects are sometimes received from the server without any member functions, but I wish to add functions for better organization. Instead of having to rely on exte ...

Using TypeScript with Vue and Pinia to access the store

Is it necessary to type the Store when importing it to TypeScript in a Pinia Vue project? // Component <p>{{ storeForm.firstName }}</p> // receiving an error "Property 'storeForm' does not exist on type" // Store ...

What is the best way to incorporate an interface in TypeScript that is both callable and has properties?

Given the scenario where an interface is defined as: interface FooWithBar { ():void; bar():void; } I am struggling with writing the implementation. I attempted the following: function foo(){ } foo.bar = function(){ }; This approach did not wo ...

Arranging three cards in a row rather than stacking them all in a single column

Struggling with React and Material UI! I have an array of 40 dynamic cards that I want to display in rows of three, but they are all rendering in a single column. The card component I'm using can be found here: https://codesandbox.io/s/r084q99q34 ...

The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a s ...

Utilize Typescript to expand the functionality of the Express Request object

Is there a way to add a custom property to the request object in Express middleware using TypeScript without resorting to bracket notation? I am struggling to find a solution that satisfies this requirement. I would ideally like to achieve something like ...

What's the best way to establish a Next.js global context without triggering a "Text content did not match" error?

I am currently working on a next.js App where I need to fetch SESSION data into a global context. This is how my code looks like: // _app.js const App = ({ Component, pageProps }) => { const start = typeof window !== 'undefined' ? window.se ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

When working in React, I encountered a problem with the for of loop, as it returned an error stating "x is undefined." Although I could easily switch to using a simple for loop, I find the for of loop to

I'm encountering an issue when using a for of loop in React, as it gives me an error stating that "x is undefined". import { useEffect } from "react"; export default function HomeContent() { useEffect(() => { let content = document ...

The Nextjs framework is experiencing a high total blocking time in its *****.js chunk

As I analyze the performance of next.js in my project, I am noticing a high total blocking time. Specifically, the "framework" chunk consistently takes more than 50ms. It seems that this chunk corresponds to the react and react-dom JavaScript files. Does ...

error - Uncaught ReferenceError: Unable to use 'auth' before initializing

I am currently following an online tutorial on building a WhatsApp clone and I encountered a problem. import "../styles/globals.css"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../f ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Utilizing form data to upload images and send them back to the front end within a React js application

I am working on a project using NestJS and React JS to create an image uploader. In React, I have the following setup: const props = { onChange({ file, fileList }: any) { const fd = new FormData(); fd.append('img& ...

Refresh the page after deploying Next.js Link

After updating to the latest version of Next.js, I noticed that when deploying (using Firebase) and trying to navigate the page, it completely refreshes, which does not happen locally. const CustomLink = ({ children, page, ...props }) => ( <Link cl ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

What is the method for defining a function within a TypeScript namespace?

Suppose there is a namespace specified in the file global.d.ts containing a function like this: declare namespace MY_NAMESPACE { function doSomething(): void } What would be the appropriate way to define and describe this function? ...