Skip to content

custom control with dynamic option #6043 #6044

Open
@pavarun-topgun

Description

@pavarun-topgun

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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    issue/bug-unconfirmedIssues that describe a bug that hasn't been confirmed by a maintainer yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions