Search code examples
javascriptreactjsreact-hooksreact-selectreact-virtualized

searchable dropdown in react


I have below list in react.

<select
    id="sponsor" 
    name="sponsor"
    className="form-control"
    placeholder="Sponsor"
    }
    >
    <option value="" selected>Please select the sponsor</option>
     {
     active && result.map((sponsor:Sponsor,index:number)=>
          <option  value={sponsor.id} >{sponsor.name}</option>    
      )
    }

</select>

it is working perfectly fine. now I need to change it to searchable list. I did below.

     import VirtualizedSelect from 'react-virtualized-select'
    import "react-virtualized-select/styles.css";
    import 'react-virtualized/styles.css'
     

 <VirtualizedSelect
        id="sponsor" 
        name="sponsor"
        className="form-control"
        placeholder="Sponsor"
        options={ active && result.map((sponsor:Sponsor,index:number)=>
            {sponsor.name}
          
        )}

     >
       </VirtualizedSelect> 

now nothing is coming in list. basically my requirement is to make list searchable and insert data of API into that list.

Could you please help me with same? Any other option will also be very helpful

Edit1:-

I need list like below. first line "Please choose sponsor"

enter image description here


Solution

  • according to VirtualizedSelect docs here https://www.npmjs.com/package/react-virtualized-select, the component accept array of objects like :

        const options = [
          { label: "One", value: 1 },
          { label: "Two", value: 2 },
          { label: "Three", value: 3, disabled: true }
          // And so on...
        ]
    

    not array of strings and I think this is way its not working, I'd suggest to change your code to :

     <VirtualizedSelect
            id="sponsor" 
            name="sponsor"
            className="form-control"
            placeholder="Sponsor"
            options={ active && result.map((sponsor:Sponsor,index:number)=>
                ({label: sponsor.name, value: sponsor.name})
              
            )}
    
         >
           </VirtualizedSelect>