adobe / react-spectrum

A collection of libraries and tools that help you build adaptive, accessible, and robust user experiences.
https://react-spectrum.adobe.com
Apache License 2.0
12.9k stars 1.12k forks source link

How to use useHover and useFocus together without overriding the props returned by the first hook? #1503

Closed asterikx closed 3 years ago

asterikx commented 3 years ago

❔ Question

I need to read hover and focus state of a component and its descendants. How can I use useHover and useFocus together without overriding the props returned by the first hook? E.g. in the example below, {...focusProps} will override (some of) the props in {...hoverProps}.

🔦 Context

I have carousel component with auto-play. It should pause if it is hovered (and continue playing if unhovered). On interaction (i.e. on focus), it should stop playing too.

💻 Code Sample


const { hoverProps } = useHover({/* ... */});
const { focusProps } = useFocus({/* ... */});

return (
  <div {...hoverProps} {...focusProps}>
    {children}
  </div>
)
snowystinger commented 3 years ago

You can use our utility function, mergeProps. This will chain together any handler functions so that they are all called https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/utils/src/mergeProps.ts

asterikx commented 3 years ago

Thank you very much! (And sorry for not reading the docs thoroughly.)

karanshah229 commented 1 year ago

@asterikx Can you provide some information on how you built a carousel using react-spectrum.