useMergeRefs

A utility for merging multiple refs.

Use this Hook to work with multiple refs to the same DOM element. The order of refs matters and refs are called from left to right.

import { useMergeRefs } from 'react-gui/use-merge-refs';

const ref = useMergeRefs(refA, refB);

API #

Return value #

useMergeRefs returns a React callback ref.

ref (?HTMLElement) => void

A callback ref that must be passed to the target element.


Examples #

Any number of refs can be merged together. This is particularly useful when working with multiple interaction hooks, e.g., custom combinations and interaction state management.

function useInteractionState() {
const [ hovering, onHoverChange ] = useState(false);
const [ focusing, onFocusChange ] = useState(false);
const [ pressing, onPressChange ] = useState(false);
const hoverRef = useHover({ onHoverChange });
const focusRef = useFocus({ onFocusChange });
const pressRef = usePress({ onPressChange });

const ref = useMergeRefs(hoverRef, focusRef, pressRef);
const state = { hovering, focusing, pressing };

return [ref, state];
}

function Component(props) {
const [ref, state] = useInteractionState();
const style = { backgroundColor: state.pressed ? 'lightgray' : 'white' };
return (
<div
children={props.children}
ref={ref}
style={style}
/>

);
}
Updated
Edit
React GUICopyright © Facebook Inc.