apps/mantine.dev/src/pages/hooks/use-click-outside.mdx
import { UseClickOutsideDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.useClickOutside);
The use-click-outside hook accepts 3 arguments:
handler – function that is called when clicking outsideevents – optional list of events that trigger outside click, ['mousedown', 'touchstart'] by defaultnodes - optional list of nodes that should not trigger outside click eventenabled - optional boolean to dynamically enable/disable the listener, true by defaultThe hook returns a ref object that must be passed to the element
based 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} />;
}
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:
// Will work only with useState, not useRef
import { useState } from 'react';
import { Portal } from '@mantine/core';
import { useClickOutside } from '@mantine/hooks';
function Demo() {
const [dropdown, setDropdown] = useState<HTMLDivElement | null>(
null
);
const [control, setControl] = useState<HTMLDivElement | null>(null);
useClickOutside(() => console.log('outside'), null, [
control,
dropdown,
]);
return (
// We cannot use root element ref as it does not contain dropdown
<div>
<div ref={setControl}>Control</div>
<Portal>
<div ref={setDropdown}>Dropdown</div>
</Portal>
</div>
);
}
import { useClickOutside } from '@mantine/hooks';
const ref = useClickOutside<HTMLDivElement>(() =>
console.log('Click outside')
);
function useClickOutside<T extends HTMLElement = any>(
handler: (event: MouseEvent | TouchEvent) => void,
events?: string[] | null,
nodes?: (HTMLElement | null)[],
enabled?: boolean
): React.RefObject<T>;