Refactor Dropdown component: integrate useOutsideClick for improved click handling, manage dropdown state with useRef and useState, and enhance button functionality for better user experience.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
import { FC, useEffect, useState } from "react";
|
||||
import { useOutsideClick } from "@/hooks/useOutsideClick";
|
||||
import { FC, useEffect, useRef, useState } from "react";
|
||||
import { FaFilter } from "react-icons/fa";
|
||||
|
||||
type Props = {
|
||||
@@ -12,19 +13,31 @@ type Props = {
|
||||
};
|
||||
|
||||
export const Dropdown: FC<Props> = ({ items, defaultValue, callback }) => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [value, setValue] = useState<string>(defaultValue);
|
||||
|
||||
useOutsideClick(ref, () => setIsOpen(false));
|
||||
|
||||
useEffect(() => {
|
||||
callback?.(value);
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<div className="relative inline-block">
|
||||
<button className="focus:[&+div]:opacity-100 relative z-10 block p-2 shadow-sm cursor-pointer bg-white text-primary rounded-md">
|
||||
<div ref={ref} className="relative inline-block">
|
||||
<button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="relative z-10 block p-2 shadow-sm cursor-pointer bg-white text-primary rounded-md"
|
||||
>
|
||||
<FaFilter />
|
||||
</button>
|
||||
|
||||
<div className="absolute left-0 z-20 w-48 py-2 mt-2 origin-top-right bg-white rounded-md shadow-xl dark:bg-gray-800 opacity-0">
|
||||
<div
|
||||
className="absolute left-0 z-20 w-48 py-2 mt-2 origin-top-right bg-white rounded-md shadow-xl dark:bg-gray-800"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<p
|
||||
key={item.value}
|
||||
|
||||
Reference in New Issue
Block a user