How to get value from React Select Form
Asked Answered
C

2

9

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.

Cottle answered 12/2, 2022 at 18:15 Comment(2)
Does this answer your question? Use jQuery to get text of targetHomogamy
codegrepper.com/code-examples/javascript/react+select+onchangeConsistence
C
14

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

Ciliolate answered 12/2, 2022 at 18:29 Comment(3)
@Faisal Nazik, check this out !!Ciliolate
Yes this is returning data in this format {value: 'YES', label: 'Set to Active'} label: "Set to Active" value: "YES" [[Prototype]]: ObjectCottle
This helped me a lot, so thank you!Asphyxia
F
0

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

Fructify answered 2/3, 2023 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.