useMergeRefs is a custom hook used to merge several react refs into a single one.
Import
import { useMergeRefs } from '@passfort/castle'
Return value
The useMergeRefs hook returns a function that receives the element and assign the value to the given React refs.
Usage
function Example({ ref, ...props }) {
const internalRef = React.useRef()
const refs = useMergeRefs(internalRef, ref)
return (
<div {...props} ref={refs}>
A div with multiple refs.
</div>
)
}
live example
Usage combining with another Chakra-UI hooks
You can see how events on different refs reflect on the combined ref, on the same element.
function Example() {
const internalRef = React.useRef(null)
const externalRef = React.useRef(null)
const combinedRef = useMergeRefs(internalRef, externalRef)
useOutsideClick({
ref: internalRef,
handler: () => {
log('Clicked outside the box!')
},
})
const focusBox = () => {
if (externalRef.current) {
externalRef.current.focus()
log('Box focused programmatically!')
}
}
return (
<Box>
<Button onClick={focusBox} colorScheme="teal" mb={4}>
Focus the Box
</Button>
<Box
ref={combinedRef}
tabIndex={0}
bg="B25"
p={4}
borderRadius="md"
boxShadow="md"
_focus={{ outline: '2px solid', outlineColor: 'R100' }}
onClick={() => log('Clicked inside the box!')}
>
Click outside to close. Use the button to focus this box.
</Box>
</Box>
)
}
live example