Skip to content

Commit a623d5d

Browse files
committed
fix RefComponent update of existing elements
1 parent cc6a764 commit a623d5d

1 file changed

Lines changed: 12 additions & 9 deletions

File tree

src/ref-component.tsx

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,18 @@ type RefUpdate = (ref: HTMLElement) => void
44
type BaseProps = { init: RefUpdate, unmount: RefUpdate } & Record<string, unknown>
55

66
export function RefComponent<Props extends BaseProps>({ init, unmount, ...props }: Props) {
7-
const r = React.useRef<HTMLSpanElement | null>()
7+
const ref = React.useRef<HTMLSpanElement>(null)
88

9-
return <span {...props} ref={ref => {
10-
if (r.current) {
11-
unmount(r.current)
12-
}
13-
if (ref) {
14-
r.current = ref
15-
init(ref)
9+
React.useEffect(() => {
10+
const element = ref.current
11+
12+
return () => {
13+
if (element) unmount(element)
1614
}
17-
}}/>
15+
}, [])
16+
React.useEffect(() => {
17+
if (ref.current) init(ref.current)
18+
})
19+
20+
return <span {...props} ref={ref} />
1821
}

0 commit comments

Comments
 (0)