From 4c1b757403b676287eab222248fd38cc6e18adba Mon Sep 17 00:00:00 2001 From: Blaster4385 Date: Wed, 15 May 2024 12:53:04 +0530 Subject: feat: close language dropdown on clicking outside it --- client/src/components/CustomSelect/CustomSelect.jsx | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/client/src/components/CustomSelect/CustomSelect.jsx b/client/src/components/CustomSelect/CustomSelect.jsx index f588d38..3155700 100644 --- a/client/src/components/CustomSelect/CustomSelect.jsx +++ b/client/src/components/CustomSelect/CustomSelect.jsx @@ -1,4 +1,4 @@ -import React, { useState } from "react"; +import React, { useEffect, useState, useRef } from "react"; import styles from "./CustomSelect.module.css"; const CustomSelect = ({ options, onSelect }) => { @@ -6,6 +6,7 @@ const CustomSelect = ({ options, onSelect }) => { const [selectedOption, setSelectedOption] = useState( options.length > 0 ? options[0] : null, ); + const selectRef = useRef(null); const toggleDropdown = () => { setIsOpen(!isOpen); @@ -17,8 +18,21 @@ const CustomSelect = ({ options, onSelect }) => { setIsOpen(false); }; + const handleClickOutside = (event) => { + if (selectRef.current && !selectRef.current.contains(event.target)) { + setIsOpen(false); + } + }; + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, []); + return ( -
+
{selectedOption ? ( <> -- cgit v1.2.3-73-gaa49b