How to handle click outside a component in React?

One way to handle a click outside a component in React is by creating a ref for the component and then using the document click event listener to detect clicks outside the component. Here's an example of how you can achieve this:

import React, { useRef, useEffect } from 'react'; const OutsideClickHandler = ({ children, onOutsideClick }) => { const ref = useRef(); const handleClickOutside = (event) => { if (ref.current && !ref.current.contains(event.target)) { onOutsideClick(); } }; useEffect(() => { document.addEventListener('click', handleClickOutside); return () => { document.removeEventListener('click', handleClickOutside); }; }, []); return <div ref={ref}>{children}</div>; }; export default OutsideClickHandler;

In this example, we create a OutsideClickHandler component that takes in two props: children and onOutsideClick. The children prop represents the content of the component that we want to detect clicks outside of, while the onOutsideClick prop is a callback function that will be triggered when a click outside the component is detected.

We use the useRef hook to create a ref for the component and the useEffect hook to add a click event listener to the document. In the handleClickOutside function, we check if the click event target is not within the component's ref, and if so, we call the onOutsideClick callback function.

To use the OutsideClickHandler component, you can wrap the content you want to detect clicks outside of, like so:

<OutsideClickHandler onOutsideClick={handleOutsideClick}> <div>Click outside me!</div> </OutsideClickHandler>

In this example, handleOutsideClick is the callback function that will be triggered when a click is detected outside the component.