Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from React Select Form

Sorry for just a basic question, But I'm a little stuck here to find any way to get values from React Select after making a selection.

This is a Simple Selection setup.

    const selectOptions = [
            { value: 'YES', label: 'Set to Active' },
            { value: 'NO', label: 'Set to Mute' }
       ]

    <Label className='form-label'>Select</Label>
         <Select
            isClearable={false}
            className='react-select'
            classNamePrefix='select'
            options={selectOptions}
            theme={selectThemeColors}
          />

I want to get the value against user-selected choice and put it into userChoice content using useState.

const [userChoice, setUserChoice] = useState("")

value can be YES or NO as defined in selectOptions. But how to pass this into userChoice. I tried using onChange={(e) => setUserChoice(e.target.value)} But this thing is not working.

Also tried onInputChange={handleInputChange} as suggested in previously asked threads on StackOverflow but not working here.

like image 411
Faisal Nazik Avatar asked Apr 23 '26 05:04

Faisal Nazik


2 Answers

The onChange callback handler gets called with the whole choice object instead of the event object. Therefore it should be like this.

 <Select
      ...
      ...
      onChange={(choice) => setUserChoice(choice)}
 />

If you only intested in YES / NO value, then use,

onChange={(choice) => setUserChoice(choice.value)}

Edit exciting-bouman-gu4yj

like image 198
Amila Senadheera Avatar answered Apr 24 '26 18:04

Amila Senadheera


if you want the id or int value instead of the text make sure you set the value to the id and the text to the string value. if you are using forms directly you can can it directly by e.target.value

<select id="branch" className="form-control" name='branch' } >
 {branch.map(e => (<option key={e.id}  value={e.id}   selected= >{e.branch}</option>))}   
                                </select>

then call it directly in a function

const UpdateSubmit (e)=>{
        alert(e.target.branch.value)
........
}

if you dont do so you will get only String value

like image 43
mumbasa Avatar answered Apr 24 '26 18:04

mumbasa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!