Home > Net >  searchable dropdown list in react
searchable dropdown list in react

Time:03-11

I have serchable dropdown list in react. for that I have used VirtualizedSelect the problem is onChange is not working.

import VirtualizedSelect from 'react-virtualized-select'
import "react-virtualized-select/styles.css";
import 'react-virtualized/styles.css'
<VirtualizedSelect
       id="sponsor" 
       name="sponsor"
       defaultValue="Please"
       className="form-control"
       placeholder="Sponsor"
       options=  { active && result.map((sponsor:Sponsor,index:number)=>
           ({label: sponsor.name, value: sponsor.name})
       
       )} 
       onChange={ (e:any)=>{printValue(e)}}
        }>
</VirtualizedSelect>

inside the printValue I am printing alert(e.target.value) and it is printing undefined.

const printValue=(e:any)=>{
    alert("value is" e.target.value);
}

also as of now list is coming like below.

enter image description here

I want it to make like below. I mean I want to add "Please select the sponsor" enter image description here

can you please help me on the same? if I am printing console.log(e.target.value) inside the method. it is throwing below error.

enter image description here

Edit1:- it is coming like below.

enter image description here

CodePudding user response:

This is how you could approach this:

import React, { useState } from "react"

import VirtualizedSelect from 'react-virtualized-select'

function App() {

  const options = [
    { label: "One", value: 1 },
    { label: "Two", value: 2 },
    { label: "Three", value: 3 },
    { label: "Four", value: 4 },
    { label: "Five", value: 5 },
    { label: "Six", value: 6 }
  ]

  const [item, setItem] = useState(null)

  return (
    <>
      <VirtualizedSelect
        options={options}
        onChange={(value) => setItem(value)}
        value={item}
      />
    </>
  )
}

export default App;

Edit 1:

Import the default styles which are these lines in your component

import 'react-select/dist/react-select.css'
import 'react-virtualized/styles.css'
import 'react-virtualized-select/styles.css'

Edit 2: react-select v2 upwards don't provide the css file due to various reasons. One of the way is to add the css file manually by copy-pasting which I suggested.

Screenshot proof: Screenshot

  • Related