use-click-outside

Detect click and touch events outside of specified element
Import

Usage

import React, { useState } from 'react';
import { Paper, Button } from '@mantine/core';
import { useClickOutside } from '@mantine/hooks';
export function Demo() {
const [opened, setOpened] = useState(false);
const ref = useClickOutside(() => setOpened(false));
return (
<>
<Button onClick={() => setOpened(true)}>Open dropdown</Button>
{opened && (
<Paper elementRef={ref} shadow="sm">
<span>Click outside to close</span>
</Paper>
)}
</>
);
}

API

Hook accepts 2 arguments:

  • handler – function that will be called on outside click
  • events – optional list of events that indicate outside click

Hook returns React ref object that should be passed to element on which outside clicks should be captured.

import { useClickOutside } from '@mantine/hooks';
function Example() {
const handleClickOutside = () => console.log('Clicked outside of div');
const ref = useClickOutside(handleClickOutside);
return <div ref={ref} />;
}

Change events

By default use-click-outside listens to mousedown and touchstart events, you can change these events by passing an array of events as second argument:

import React, { useState } from 'react';
import { Paper, Button } from '@mantine/core';
import { useClickOutside } from '@mantine/hooks';
export function Demo() {
const [opened, setOpened] = useState(false);
const ref = useClickOutside(() => setOpened(false), ['mouseup', 'touchend']);
return (
<>
<Button onClick={() => setOpened(true)}>Open dropdown</Button>
{opened && (
<Paper elementRef={ref} shadow="sm">
<span>Click outside to close</span>
</Paper>
)}
</>
);
}

TypeScript

Definition

function useClickOutside<T extends HTMLElement = any>(
handler: () => void,
events: string[] = ['mousedown', 'touchstart']
): React.MutableRefObject<T>;

Ref type

By default use-click-outside returns ref object with React.MutableRefObject<any> type as ref type does not matter in almost all cases. You can specify ref type by passing a type:

const ref = useClickOutside<HTMLDivElement>(onClickOutside);