diff --git a/src/components/Buttons/Filter.js b/src/components/Buttons/Filter.js index 5d505cf..5ede880 100644 --- a/src/components/Buttons/Filter.js +++ b/src/components/Buttons/Filter.js @@ -1,4 +1,4 @@ -import React, { useContext } from "react"; +import React, { useContext, useEffect, useRef } from "react"; import "./Filter.css"; import { ThemeContext } from "../../Context/themeContext"; @@ -7,7 +7,7 @@ const Filter = ({ reducedState, setReducedState }) => { const [show, setShow] = React.useState(false); // Controls Popover const [filters, setFilters] = React.useState(reducedState); const { theme } = useContext(ThemeContext); - + const dropdownRef = useRef(null); function updateFilters(prop, val) { setFilters((prev) => ({ ...prev, @@ -29,10 +29,22 @@ const Filter = ({ reducedState, setReducedState }) => { setShow(false); setReducedState({ ...filters }); } + useEffect(() => { + const handleClickOutside = (event) => { + if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { + setShow(false); + } + }; + + document.addEventListener("mousedown", handleClickOutside); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, []); return ( <> -
+
{ setShow(!show); diff --git a/src/components/Buttons/Sort.js b/src/components/Buttons/Sort.js index 70a9048..8d1a473 100644 --- a/src/components/Buttons/Sort.js +++ b/src/components/Buttons/Sort.js @@ -1,4 +1,4 @@ -import React, { useContext, useEffect, useState } from "react"; +import React, { useContext, useEffect, useRef, useState } from "react"; import { ThemeContext } from "../../Context/themeContext"; const Sort = ({ setSortByForks, setSortByStars }) => { @@ -7,6 +7,7 @@ const Sort = ({ setSortByForks, setSortByStars }) => { // forksdesc, forksasc, starsdesc, starsasc, default let [sort, setSort] = useState("default"); const [show, setShow] = useState(false); + const dropdownRef = useRef(null); useEffect(() => { if (!setSortByForks || !setSortByStars) return; switch (sort) { @@ -33,9 +34,23 @@ const Sort = ({ setSortByForks, setSortByStars }) => { } }, [sort, setSortByForks, setSortByStars]); + // Close Sort Filter when clicking outside + useEffect(() => { + const handleClickOutside = (event) => { + if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { + setShow(false); + } + }; + + document.addEventListener("mousedown", handleClickOutside); + + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, []); return ( <> -
+
{ setShow(!show);