Skip to content

Commit 091b055

Browse files
committed
feat: forward ref to inner canvas
BREAKING CHANGE: wrap default export in forwardRef
1 parent d72cac9 commit 091b055

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

src/ReactConfetti.tsx

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
import React, { Component, CanvasHTMLAttributes } from 'react'
22
import Confetti, { IConfettiOptions, confettiDefaults } from './Confetti'
33

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+
}
59

610
export class ReactConfetti extends Component<Props> {
711
static readonly defaultProps = {
812
...confettiDefaults,
913
}
1014

15+
constructor(props: Props, ...rest: any[]) {
16+
super(props, ...rest)
17+
this.canvas = props.canvasRef || React.createRef<HTMLCanvasElement>()
18+
}
19+
1120
canvas: React.RefObject<HTMLCanvasElement> = React.createRef()
1221
confetti?: Confetti
1322

@@ -53,19 +62,28 @@ export class ReactConfetti extends Component<Props> {
5362
}
5463
}
5564

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] {
5769
const confettiOptions: Partial<IConfettiOptions> = {}
70+
const refs: Refs = {}
5871
const rest: any = {}
5972
const confettiOptionKeys = [...Object.keys(confettiDefaults), 'confettiSource', 'drawShape', 'onConfettiComplete']
73+
const refProps = ['canvasRef']
6074
for(const prop in props) {
6175
const val = props[prop as string]
6276
if(confettiOptionKeys.includes(prop)) {
6377
confettiOptions[prop as keyof IConfettiOptions] = val
78+
} else if(refProps.includes(prop)) {
79+
refProps[prop as any] = val
6480
} else {
6581
rest[prop] = val
6682
}
6783
}
68-
return [confettiOptions, rest]
84+
return [confettiOptions, rest, refs]
6985
}
7086

71-
export default ReactConfetti
87+
export default React.forwardRef<Ref, Props>((props, ref) => (
88+
<ReactConfetti canvasRef={ref} {...props} />
89+
))

0 commit comments

Comments
 (0)