daniel-lundin / react-dom-confetti

Trigger confetti explosions on state transitions
624 stars 30 forks source link

Confetti on initial load #16

Open VisheshSingh opened 5 years ago

VisheshSingh commented 5 years ago

Hey,

I was able to get it to work upon a state change. Wondering if there is a way to make the confetti appear when a component loads initially without any state change. I tried setting the active attribute to true but that didn't work. Help will be appreciated!

RXminuS commented 5 years ago

Hooks to the rescue :-)

const Yay : React.FC<{}> = () => {
  const trigger = useBoolean(false);
  useEffect(() => {
    setTimeout(trigger.setTrue, 300);
    //eslint-disable-next-line
  }, [])
  return (<Confetti active={trigger.value} config={confettiConfig} />);
}
AdiBev commented 4 years ago

Is there way to do this without hooks?

mjoyce91 commented 4 years ago

@AdiBev you could put it inside componentDidMount. Untested example:

this.state = {
  active: false
}
componentDidMount() {
  setTimeout(() => {
    this.setState({ active: true });
  }, 300);
}
...

You probably don't even need the timeout if you use it within a componentDidMount.

gunar commented 4 years ago

Alternatively, we can drop the setTimeout and use a callback ref to trigger the animation as soon as the component renders:

const Component = () => {
  const [active, setActive] = useState(false);
  return (
    <Confetti
      ref={() => { setActive(true) }}
      active={active}
      config={confettiConfig}
    />);
}
MartinDevillers commented 3 years ago

This is the first thing I ran in as well. I kind of expected <Confetti active /> to start throwing me some confetti ;-) I fixed it by wiring the active prop to some hook that changes pretty early in my components lifecycle. The document is clear though: the effect is triggered when the active prop changes from falsy to truthy. It's the change that triggers it; not the actual value.