Gesture Support in React with Motion

Dec 19, 2024

Gestures | Motion for React (previously Framer Motion)

Overview

  • Motion extends React's event listeners with a set of UI gestures.
  • Supported gestures: hover, tap, pan, drag, and inView.

Gesture Animation Props

  • motion components provide various gesture animation props:
    • whileHover
    • whileTap
    • whileFocus
    • whileDrag
    • whileInView

Example

<motion.button
  whileHover={{ scale: 1.2, transition: { duration: 1 } }}
  whileTap={{ scale: 0.9 }}
/>
  • Props can either be set as target values or names of variants defined via the variants prop.

Example with Variants

<motion.button
  whileTap="tap"
  whileHover="hover"
  variants={buttonVariants}
>
  <svg>
    <motion.path variants={iconVariants} />
  </svg>
</motion.button>

Gestures

Hover

  • Detects pointer hover over/leave a component.
  • Only fires with actual mouse events.

Example

<motion.a
  whileHover={{ scale: 1.2 }}
  onHoverStart={event => {}}
  onHoverEnd={event => {}}
/>

Tap

  • Detects primary pointer press/release on the same component.
  • Events:
    • tap: Fires when the tap ends on the same component.
    • tapCancel: Fires if the tap ends outside the component.

Example

<motion.button whileTap={{ scale: 0.9, rotate: 3 }} />

Accessibility

  • Elements with tap events are keyboard-accessible.
  • Enter triggers tap events on focused elements.

Pan

  • Recognizes pointer press and movement beyond 3 pixels.
  • Ends when the pointer is released.

Example

<motion.div onPan={(e, pointInfo) => {}} />

Drag

  • Applies pointer movement to the component's x/y axis.
  • Default behavior includes inertia animation on drag end.

Example

<motion.div drag whileDrag={{ scale: 1.2, backgroundColor: "#f00" }} />
  • Drag constraints can be set using pixel values or refs.

Focus

  • Detects when a component gains/loses focus.

Example

<motion.a whileFocus={{ scale: 1.2 }} href="#" />

Event Propagation

  • Children can prevent pointer events from propagating using Capture React props.

Example

<motion.div whileTap={{ scale: 2 }}>
  <button onPointerDownCapture={e => e.stopPropagation()} />
</motion.div>

Note on SVG Filters

  • Gestures not recognized on SVG filter components.
  • Instead, use while- props and event handlers on parent elements with variants.