Skip to content

Commit

Permalink
Stage 7: Replaced the functional component with class component.
Browse files Browse the repository at this point in the history
This solved the callback cancellations problem as componentWillUnmount will have access to state and on componentDidMount I am storing the canvas in component's state.
  • Loading branch information
A M Akankshit authored and A M Akankshit committed Oct 31, 2020
1 parent 8f7607b commit e9dfbc9
Showing 1 changed file with 44 additions and 31 deletions.
75 changes: 44 additions & 31 deletions src/confetti/index.js
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { Component, createRef } from 'react';

const globalThis = window;
const { requestAnimationFrame, cancelAnimationFrame } = globalThis;
Expand Down Expand Up @@ -138,39 +138,52 @@ class BridalConfetti {
}
}

const Confetti = ({ styles = {}, options = {}, streamAnimation }) => {
const canvasRef = useRef(null);
const [canvas, setCanvas] = useState(null);

useEffect(() => {
setCanvas(new BridalConfetti(canvasRef.current, options));

return () => {
canvas.ummountCanvas();
class Confetti extends Component {
constructor(props) {
super(props);
this.canvasRef = createRef();
this.state = {
canvas: null
};
}, []);
}

useEffect(() => {
if (canvas) {
if (streamAnimation) {
canvas.startAnimation();
} else {
// This will not work. Because canvas will be set to null befor this is invoked.
canvas.stopAnimation();
}
componentDidMount() {
const canvas = new BridalConfetti(
this.canvasRef.current,
this.props.options
);
if (this.props.streamAnimation === true) {
canvas.startAnimation();
}
}, [streamAnimation, canvas]);
this.setState({ canvas });
}

return (
<canvas
ref={canvasRef}
style={{
height: '100%',
width: '100%',
...styles
}}
/>
);
};
componentDidUpdate() {
const { streamAnimation } = this.props;
if (streamAnimation) {
this.state.canvas.startAnimation();
} else {
this.state.canvas.stopAnimation();
}
}

componentWillUnmount() {
this.state.canvas.ummountCanvas();
}

render() {
const { styles } = this.props;
return (
<canvas
ref={this.canvasRef}
style={{
height: '100%',
width: '100%',
...styles
}}
/>
);
}
}

export default Confetti;

0 comments on commit e9dfbc9

Please sign in to comment.