JedWatson / JedWatson/react-select
custom control with dynamic option #6043
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 28k
- Forks
- 4.1k
- PR merge metrics
- No merged PRs in 30d
Description
I face an issue when trying to custom control in Select component and dynamically update the options based on the input value (onInputChange). The issue is I can type just only first character and the input seem to lose focus so I cannot type anything other than that. How can I solve this if the custom control is needed?
here is the example
import React, { useState } from 'react';
import Select, { components } from 'react-select';
const DynamicSelect = () => {
const [inputValue, setInputValue] = useState('');
const [selectedOption, setSelectedOption] = useState<any>(null);
const [options, setOptions] = useState<any[]>([
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'orange', label: 'Orange' }
]);
const handleInputChange = (newInputValue: string) => {
setInputValue(newInputValue);
// Dynamically generate new options or filter existing ones based on input value
const newOptions = [
{ value: `${newInputValue}_new_1`, label: `${newInputValue} New 1` },
{ value: `${newInputValue}_new_2`, label: `${newInputValue} New 2` },
];
// Optionally, filter out duplicates
setOptions(prevOptions => [
...prevOptions.filter(option => !newOptions.some(newOption => newOption.value === option.value)),
...newOptions
]);
};
// Handle the selection change
const handleSelectChange = (selected: any) => {
setSelectedOption(selected); // Set the selected option
};
return (
<div className='flex flex-row gap-10'>
<Select
components={{
Control: (props) => (
<components.Control className='flex flex-row gap-2' {...props}>
{props.children}
</components.Control>
)
}}
className='mb-10'
value={selectedOption}
onChange={handleSelectChange}
onInputChange={handleInputChange}
options={options}
isClearable
inputValue={inputValue} // Set inputValue here for typing
/>
</div>
);
};
export default DynamicSelect;
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied React/TypeScript reproduction and inspect the Select custom Control together with the controlled inputValue and onInputChange props. Done means the custom control retains focus while multiple characters are typed and dynamically generated options continue updating.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100