Last active
August 19, 2025 05:13
-
-
Save therealFoxster/4c836a01ad6f76bc4e30b8128f148543 to your computer and use it in GitHub Desktop.
A solution to get filtered options in React Select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useState } from 'react'; | |
| import Select, { components } from 'react-select'; | |
| export default function CustomSelect() { | |
| const [filteredOptions, setFilteredOptions] = useState<Options<{ value: string | number; label: string }>>([]); | |
| const currentFilteredOptions = useRef<Options<{ value: string | number; label: string }>>([]); | |
| useEffect(() => { | |
| const newOptions = currentFilteredOptions.current; | |
| if (JSON.stringify(newOptions) !== JSON.stringify(filteredOptions)) { | |
| setFilteredOptions(newOptions); | |
| } | |
| }); | |
| return ( | |
| <Select | |
| ... | |
| components={{ | |
| MenuList: CustomMenuList, | |
| }} | |
| /> | |
| ); | |
| function CustomMenuList(props: any) { | |
| currentFilteredOptions.current = Array.isArray(props.children) | |
| ? props.children.map((child: any) => child.props.data) | |
| : []; | |
| return <components.MenuList {...props} />; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment