This weekend, I tried to build a Search component myself using React. Before doing that, I needed to build an input select component but I decided to build it from scratch using Div as I need to apply my own style to it. When I click on a Div, I am gonna show the list of some items. And if I click outside of that list items, it can be hidden. Also, when I click the Div again(when a list item is open), I want to hide that list item too. But it doesn't work. I am using this code.
import { useState, useRef, useEffect } from 'react';
function useVisible(initialIsVisible = false) {
const [isVisible, setIsVisible] = useState(initialIsVisible);
const ref = useRef(null);
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsVisible(false);
}
};
useEffect(() => {
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
};
}, []);
return { ref, isVisible, setIsVisible };
}
export default useVisible;
Hey, Nemanja Lazarevic
Here it is:
import React from 'react';
import useVisible from './useVisible';
// In the component
const { ref, isVisible, setIsVisible } = useVisible();
// In return
<div onClick={setIsVisible}>
Select items
</div>
{isVisible && (
<div ref={ref}>
// list items here
</div>
)}