Skip to content

Commit 8848fa0

Browse files
committed
fix: ref is undefined
1 parent 26ed0da commit 8848fa0

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/CChart.tsx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import PropTypes from 'prop-types'
22
import React, {
33
forwardRef,
44
HTMLAttributes,
5+
MutableRefObject,
56
useEffect,
67
useImperativeHandle,
78
useMemo,
@@ -110,6 +111,16 @@ export interface CChartProps extends HTMLAttributes<HTMLCanvasElement | HTMLDivE
110111
wrapper?: boolean
111112
}
112113

114+
type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null
115+
116+
const reforwardRef = <T,>(ref: ForwardedRef<T>, value: T) => {
117+
if (typeof ref === 'function') {
118+
ref(value)
119+
} else if (ref) {
120+
ref.current = value
121+
}
122+
}
123+
113124
export const CChart = forwardRef<ChartJS | undefined, CChartProps>(
114125
(
115126
{
@@ -180,6 +191,8 @@ export const CChart = forwardRef<ChartJS | undefined, CChartProps>(
180191
options: computedOptions,
181192
plugins,
182193
})
194+
195+
reforwardRef(ref, chartRef.current)
183196
}
184197

185198
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -253,6 +266,8 @@ export const CChart = forwardRef<ChartJS | undefined, CChartProps>(
253266
}
254267

255268
const destroyChart = () => {
269+
reforwardRef(ref, null)
270+
256271
if (chartRef.current) {
257272
chartRef.current.destroy()
258273
chartRef.current = undefined

0 commit comments

Comments
 (0)