FezVrasta/popper.js

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

Summary

Maintainability
Test Coverage
<PageCard>

# useClick

Opens or closes the floating element when clicking the reference
element.

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

<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 click = useClick(context);

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

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

## Props

```ts
interface UseClickProps {
  enabled?: boolean;
  event?: 'click' | 'mousedown';
  toggle?: boolean;
  ignoreMouse?: boolean;
  keyboardHandlers?: boolean;
}
```

### `enabled{:.key}`

default: `true{:js}`

Conditionally enable/disable the Hook.

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

### `event{:.key}`

default: `'click'{:js}`

The type of event to use to determine a "click" with mouse input.
Keyboard clicks work as normal.

```js
useClick(context, {
  event: 'mousedown',
});
```

### `toggle{:.key}`

default: `true{:js}`

Whether to toggle the open state with repeated clicks.

```js
useClick(context, {
  toggle: false,
});
```

### `ignoreMouse{:.key}`

default: `false{:js}`

Whether to ignore the logic for mouse input (for example, if
`useHover(){:js}` is also being used).

When `useHover(){:js}` and `useClick(){:js}` are used together,
clicking the reference element after hovering it will keep the
floating element open even once the cursor leaves. This may be
not be desirable in some cases.

```js
useClick(context, {
  ignoreMouse: true,
});
```

### `keyboardHandlers{:.key}`

default: `true{:js}`

Whether to add keyboard handlers (`Enter` and `Space` key
functionality) for non-button elements (to open/close the
floating element via keyboard "click").

```js
useClick(context, {
  keyboardHandlers: false,
});
```