useOutsideClick

分类:

other

日期:

2022-3-02

标签:

chakra

useOutsideClick is a custom hook that handles click events outside a specific DOM element, like a div. A handler is invoked when a click or touch event happens outside the referenced element.

This hook is compatible with mouse and touch events.

Import#

import { useOutsideClick } from '@chakra-ui/react';

Usage#

function Example() {
const ref = React.useRef();
const [isModalOpen, setIsModalOpen] = React.useState(false);
useOutsideClick({
ref: ref,
handler: () => setIsModalOpen(false),
});
return (
<>
{isModalOpen ? (
<div ref={ref}>
👋 Hey, I'm a modal. Click anywhere outside of me to close.
</div>
) : (
<button onClick={() => setIsModalOpen(true)}>Open Modal</button>
)}
</>
);
}

Parameters#

The useOutsideClick hook accepts an object with the following properties:

ref

The reference to a DOM element.

RefObject<HTMLElement>

enabled

Whether the hook is enabled

boolean

handler

Function invoked when a click is triggered outside the referenced element.

((e: Event) => void)
footer logo

© 2022 Designed with chakra ui. Powered by contentlayerjs and nextjs etc. All rights reserved

TwitterYouTubeGithub