alampros / react-confetti

Confetti without the cleanup.
http://alampros.github.io/react-confetti/
MIT License
1.51k stars 99 forks source link

in my next.js app it doesn't get width / height on initial load #128

Closed allenchuang closed 2 years ago

allenchuang commented 2 years ago

following the example here:

import React from 'react'
import useWindowSize from 'react-use/lib/useWindowSize'
import Confetti from 'react-confetti'

export default () => {
  const { width, height } = useWindowSize()
  return (
    <Confetti
      width={width}
      height={height}
    />
  )
}

the confetti is still showing the default width and height on initial load. (I'm using nextJS and attaching the component at my index.js file.

image
AndrewNow commented 2 years ago

Having the same issue on Next.js! Have you managed to find a fix?

AndrewNow commented 2 years ago

I ended up using this package instead, which seemed to work better for me: https://www.npmjs.com/package/react-rewards

alampros commented 2 years ago

I'm not too familiar with Next.js, but I would try gating the initialization in a useEffect so it runs after the initial page load.

davekiss commented 2 years ago

Here's a little trick for getting this working as expected in Next applications:

import React from 'react';
import Celebration from 'react-confetti';
import { useWindowSize } from 'react-use';

const Confetti = () => {
  const { width, height } = useWindowSize();
  const [isClient, setClient] = React.useState(false);

  React.useEffect(() => {
    setClient(true);
  }, [])

  return (
    <>
      {isClient && <Celebration width={width} height={height} />}
    </>
  )
}

export default Confetti;