I was trying to add a feature for a dropwdown in react, where you open the dropwdown by clicking the bottom, as usual, but i want to close the dropdown when you clik somewhere else.
Something like this:
const DropdownIcon = ({ dropdownState }) => {
return dropdownState ? <IoIosArrowDropdownCircle /> : <IoIosArrowDropup/>;
}
export const NavBar = () => {
const [dropdownState, setDropdownState] = useState(false)
const dropdownRef = useRef(null)
const toggleDropdown = () => {
setDropdownState((prevState) => !prevState);
};
return (
<span >
<button
type="button"
onClick={toggleDropdown}
ref={dropdownRef}>
<DropdownIcon dropdownState={dropdownState} />
</button>
</span>
)
}
export default NavBar
This is pretty straightfoward, but i want to add the ref attribute so i could listen to the clicks and set the value to false for whatever event.taget except for my ref HTMLelement but literally everything fails:
const DropdownIcon = ({ dropdownState }) => {
return dropdownState ? <IoIosArrowDropdownCircle /> : <IoIosArrowDropup/>;
}
export const NavBar = () => {
const [dropdownState, setDropdownState] = useState(false)
const dropdownRef = useRef(null)
const toggleDropdown = () => {
setDropdownState((prevState) => !prevState);
};
useEffect(() => { const handleClickOutside = (event) => { // Your logic here
document.addEventListener('click', handleClickOutside);
dropdownRef.current == event.target // never match
dropdownRef.current.contains(event.target) // never match
dropdownRef.current.isEqualNode(event.target) // never match
return () => {
document.removeEventListener('click', handleClickOutside);
};
}, []);
return (
<span >
<button
type="button"
onClick={toggleDropdown}
ref={dropdownRef}>
<DropdownIcon dropdownState={dropdownState} />
</button>
</span>
)
}
export default NavBar
Top comments (0)