Skip to content

Instantly share code, notes, and snippets.

@JanderSilv
Created June 20, 2024 18:17
Show Gist options
  • Save JanderSilv/41902a0331f7338bf0428ea76e5462e0 to your computer and use it in GitHub Desktop.
Save JanderSilv/41902a0331f7338bf0428ea76e5462e0 to your computer and use it in GitHub Desktop.
Simple Select with sliced options
import React, { useEffect, useRef, useState } from 'react'
import SelectAtom from 'react-select'
export const Select = (props) => {
const {
options,
onInputChange,
noOptionsMessage,
} = props
const [filteredOptions, setFilteredOptions] = useState(sliceOptions(options))
const optionsLength = options?.length || 0
const isOptionsOverLimit = optionsLength >= OPTIONS_LIMIT
const placeholderContent = isOptionsOverLimit ? 'Digite para pesquisar' : placeholder
useEffect(() => {
setFilteredOptions(sliceOptions(options))
}, [options])
const onInputChangeFilterOptions = (newValue: string, actionMeta: InputActionMeta) => {
if (isOptionsOverLimit) {
if (newValue === '') setFilteredOptions(sliceOptions(options))
if (Array.isArray(options)) {
const auxOptions = options.filter((option) => filterOption(option, newValue))
setFilteredOptions(sliceOptions(auxOptions))
}
}
if (onInputChange) onInputChange(newValue, actionMeta)
}
return (
<SelectAtom
onInputChange={onInputChangeFilterOptions}
filterOption={isOptionsOverLimit ? filterOption : undefined}
options={filteredOptions}
{...props}
/>
)
},
)
export const OPTIONS_LIMIT = 1600
export const sliceOptions = (options) => (options?.slice(0, OPTIONS_LIMIT) || [])
export const filterOption = (option, newValue) => {
if (!newValue) return true
return option.label.toLowerCase().includes(newValue.toLowerCase())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment