From 726d3e34274834126c3983f5aec1b389e323c823 Mon Sep 17 00:00:00 2001 From: n4ze3m Date: Sat, 16 Nov 2024 19:33:04 +0530 Subject: [PATCH] feat: Improve PageAssistSelect component This commit enhances the `PageAssistSelect` component with the following improvements: - Adds a `ref` to the options container to automatically scroll to the selected option when the dropdown is opened. - Fixes an issue where the `selectedOption` was not being correctly determined when the `options` array was updated. - Improves the rendering of the selected option, ensuring that the loading state, placeholder, and selected option are displayed correctly. - Adds a `data-value` attribute to the option elements to facilitate scrolling to the selected option. These changes improve the overall user experience and functionality of the `PageAssistSelect` component. --- src/components/Select/index.tsx | 40 ++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/src/components/Select/index.tsx b/src/components/Select/index.tsx index 6ccfeda..e3da503 100644 --- a/src/components/Select/index.tsx +++ b/src/components/Select/index.tsx @@ -43,6 +43,7 @@ export const PageAssistSelect: React.FC = ({ const [searchTerm, setSearchTerm] = useState("") const [filteredOptions, setFilteredOptions] = useState([]) const containerRef = useRef(null) + const optionsContainerRef = useRef(null) const [activeIndex, setActiveIndex] = useState(-1) useEffect(() => { @@ -59,6 +60,21 @@ export const PageAssistSelect: React.FC = ({ return () => document.removeEventListener("mousedown", handleClickOutside) }, []) + useEffect(() => { + try { + if (isOpen && optionsContainerRef.current && value) { + const selectedOptionElement = optionsContainerRef.current.querySelector( + `[data-value="${value}"]` + ) + if (selectedOptionElement) { + selectedOptionElement.scrollIntoView({ block: "nearest" }) + } + } + } catch (error) { + console.error("Error scrolling to selected option:", error) + } + }, [isOpen, value]) + useEffect(() => { if (!options) return @@ -193,7 +209,7 @@ export const PageAssistSelect: React.FC = ({ const selectedOption = useMemo(() => { if (!value || !options) return null - return options?.find(opt => opt.value === value) + return options?.find((opt) => opt.value === value) }, [value, options]) if (!options) { @@ -221,7 +237,13 @@ export const PageAssistSelect: React.FC = ({ className={`${defaultSelectClass} ${className}`}> {isLoading && } - {isLoading ? loadingText : selectedOption ? selectedOption.label : {placeholder}} + {isLoading ? ( + loadingText + ) : selectedOption ? ( + selectedOption.label + ) : ( + {placeholder} + )}