|
1 | 1 | import React, { Component, CanvasHTMLAttributes } from 'react'
|
2 | 2 | import Confetti, { IConfettiOptions, confettiDefaults } from './Confetti'
|
3 | 3 |
|
4 |
| -export type Props = Partial<IConfettiOptions> & CanvasHTMLAttributes<HTMLCanvasElement> |
| 4 | +export type Ref = HTMLCanvasElement |
| 5 | + |
| 6 | +export type Props = Partial<IConfettiOptions> & CanvasHTMLAttributes<HTMLCanvasElement> & { |
| 7 | + canvasRef: React.RefObject<HTMLCanvasElement> |
| 8 | +} |
5 | 9 |
|
6 | 10 | export class ReactConfetti extends Component<Props> {
|
7 | 11 | static readonly defaultProps = {
|
8 | 12 | ...confettiDefaults,
|
9 | 13 | }
|
10 | 14 |
|
| 15 | + constructor(props: Props, ...rest: any[]) { |
| 16 | + super(props, ...rest) |
| 17 | + this.canvas = props.canvasRef || React.createRef<HTMLCanvasElement>() |
| 18 | + } |
| 19 | + |
11 | 20 | canvas: React.RefObject<HTMLCanvasElement> = React.createRef()
|
12 | 21 | confetti?: Confetti
|
13 | 22 |
|
@@ -53,19 +62,28 @@ export class ReactConfetti extends Component<Props> {
|
53 | 62 | }
|
54 | 63 | }
|
55 | 64 |
|
56 |
| -function extractCanvasProps(props: Partial<IConfettiOptions> | any): [Partial<IConfettiOptions>, Partial<CanvasHTMLAttributes<HTMLCanvasElement>>] { |
| 65 | +interface Refs { |
| 66 | + [key: string]: React.Ref<HTMLElement> |
| 67 | +} |
| 68 | +function extractCanvasProps(props: Partial<IConfettiOptions> | any): [Partial<IConfettiOptions>, Partial<CanvasHTMLAttributes<HTMLCanvasElement>>, Refs] { |
57 | 69 | const confettiOptions: Partial<IConfettiOptions> = {}
|
| 70 | + const refs: Refs = {} |
58 | 71 | const rest: any = {}
|
59 | 72 | const confettiOptionKeys = [...Object.keys(confettiDefaults), 'confettiSource', 'drawShape', 'onConfettiComplete']
|
| 73 | + const refProps = ['canvasRef'] |
60 | 74 | for(const prop in props) {
|
61 | 75 | const val = props[prop as string]
|
62 | 76 | if(confettiOptionKeys.includes(prop)) {
|
63 | 77 | confettiOptions[prop as keyof IConfettiOptions] = val
|
| 78 | + } else if(refProps.includes(prop)) { |
| 79 | + refProps[prop as any] = val |
64 | 80 | } else {
|
65 | 81 | rest[prop] = val
|
66 | 82 | }
|
67 | 83 | }
|
68 |
| - return [confettiOptions, rest] |
| 84 | + return [confettiOptions, rest, refs] |
69 | 85 | }
|
70 | 86 |
|
71 |
| -export default ReactConfetti |
| 87 | +export default React.forwardRef<Ref, Props>((props, ref) => ( |
| 88 | + <ReactConfetti canvasRef={ref} {...props} /> |
| 89 | +)) |
0 commit comments