FezVrasta/popper.js

View on GitHub
website/pages/docs/useClientPoint.mdx

Summary

Maintainability
Test Coverage
<PageCard>

# useClientPoint

Positions the floating element at a given client point `(x, y)`,
usually generated by a mouse event. By default, the client's
mouse position is automatically tracked.

```js
import {useClientPoint} from '@floating-ui/react';
```

This is useful to position a floating element at a given point,
while also allowing anchoring to follow the point upon scroll.

<ShowFor packages={['react-dom']}>

<PackageLimited>@floating-ui/react only</PackageLimited>

</ShowFor>

</PageCard>

## Usage

This Hook returns event handler props.

To use it, pass it the `context{:.const}` object returned from
`useFloating(){:js}`, and then feed its result into the
`useInteractions(){:js}` array. The returned prop getters are
then spread onto the elements for rendering.

```js {9-13} /context/
function App() {
  const [isOpen, setIsOpen] = useState(false);

  const {refs, floatingStyles, context} = useFloating({
    open: isOpen,
    onOpenChange: setIsOpen,
  });

  const clientPoint = useClientPoint(context);

  const {getReferenceProps, getFloatingProps} = useInteractions([
    clientPoint,
  ]);

  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          {...getFloatingProps()}
        >
          Floating element
        </div>
      )}
    </>
  );
}
```

The default behavior is to follow the mouse cursor `clientX` and
`clientY` coordinates.

## Pointer events

If the floating element is not interactive, disable pointer
events:

```css
.floating {
  pointer-events: none;
}
```

This will ensure that the floating element does not block point
updates.

## Props

```ts
interface UseClientPointProps {
  enabled?: boolean;
  axis?: 'both' | 'x' | 'y';
  x?: number | null;
  y?: number | null;
}
```

### `enabled{:.key}`

default: `true{:js}`

Conditionally enable/disable the Hook.

```js
useClientPoint(context, {
  enabled: false,
});
```

### `axis{:.key}`

default: `'both'{:js}`

Whether to restrict the client point to an axis and use the
reference element (if it exists) as the other axis. This can be
useful if the floating element is also interactive.

```js
useClientPoint(context, {
  axis: 'x',
});
```

### `x{:.key}`

default: `null{:js}`

An explicitly defined `x` client coordinate.

```js
useClientPoint(context, {
  x: 100,
});
```

### `y{:.key}`

default: `null{:js}`

An explicitly defined `y` client coordinate.

```js
useClientPoint(context, {
  y: 100,
});
```