This can be used to synchronize the ref object with the forwarded ref and allow local access the reference instance with .current
.
The refObject
should be passed to the underlying element, NOT the forwardedRef
.
This div has a light blue outline when the ref is set
import React from 'react'
import {useRefObjectAsForwardedRef} from '@primer/react'
const ForwardedRefComponent = React.forwardRef((_props, forwardedRef) => {
const internalRef = React.useRef<HTMLDivElement>(null)
useRefObjectAsForwardedRef(forwardedRef, internalRef)
React.useEffect(() => {
if (internalRef.current) {
internalRef.current.style.border = '1px solid lightblue'
}
}, [internalRef])
return (
<div>
<div ref={internalRef}>This div has a light blue outline when the ref is set</div>
</div>
)
})
ForwardedRefComponent.displayName = 'ForwardedRefComponent'
export default function Default() {
const ref = React.useRef<HTMLDivElement>(null)
return <ForwardedRefComponent ref={ref} />
}
Loading data for useRefObjectAsForwardedRef...