useHover
Respond to hover interactions
Listen to changes in the pointer “hover” state of the element. These events are only fired for modalities that can hover over elements, e.g., ‘mouse’ interactions. Hover is not accessible to touch or keyboard interactions. Use contain
to prevent the hover state bubbling to ancestors.
import { useHover } from 'react-gui/use-hover';
const ref = useHover(hoverProps);
API #
Return value #
useHover
returns a React callback ref.
A callback ref that must be passed to the target element.
HoverProps #
By default hover events bubble. Preventing bubbling will contain the hover effect but has no effect on the bubbling of the native pointer events.
Disable the hook.
Called when the hover state of the target changes.
Called when the hover interaction begins.
Called when the hover interaction updates.
Called when the hover interaction ends.
HoverEvent #
The W3C PointerEvent for the underlying pointerenter
, pointermove
, or pointerleave
event.
Examples #
Use onHoverChange
as a convenient way to listen to changes in the hover state. For example, you might want to create a custom hook that manages the hover state.
import useHover from 'react-gui/use-hover';
function useHoverState() {
const [hovered, onHoverChange] = React.useState(false);
const ref = useHover({ onHoverChange });
return [ref, hovered];
}
The useHover
hook can be used to style elements in response to specific hover interactions. For example, you might want to change the styles used within an element’s subtree when it is hovered.
const [ref, hovered] = useHoverState();
return (
<View ref={ref}>
<Text style={[hovered && styles.textHighlight]}>
Hello world
</Text>
</View>
)
Or even change the styles of ancestors.
const [ref, hovered] = useHoverState();
return (
<View style={[hovered && styles.boxHighlight]}>
<View ref={ref}>
...
</View>
</View>
)