简体   繁体   中英

How can I store a selected value in react combobox

I created a combobox with react. How do I assign a value selected in the combobox to a variable or can I store it? Is there any example for this?

const PPP1 = props => {

    return (
      <div className='padding-div'>
          <FormGroup controlId="exampleForm.SelectCustom" className='col-8'>
              <FormLabel>1- Select Sector</FormLabel>
              <FormControl as="select" custom>
                  <option> </option>
                  <option>Agriculture</option>
                  <option>Mining</option>
                  <option>Information</option>
                  <option>Finance</option>
                  <option>Real Estate</option>
                  <option>Other</option>
              </FormControl>
          </FormGroup>

      </div>
    )
}

export default PPP1

If the FormControl object is rendered into a regular <select> tag, you could do the following:

Declare your state:

state = { 
    selectedData: '',
}

Then implement onChange function:

onChange = e => {
    this.setState({ selectedData: e.target.value });
}

And then bind the function:

<FormControl as="select" custom onChange={ this.onChange} >

In the end, you could access the result, calling this.state.selectedData

Edit: I didn't notice that you use Function component, my solution is for a class component, but it could be easily translated. Please let me know if you need help doing that.

You might considering adding onChange props on FormControl component. Ie on this

  const handleChange = (event) => {
setState({ ...state, [event.target.name]: event.target.checked });}

<FormControlLabel
            control={<Checkbox checked={gilad} onChange={handleChange} name="gilad" />}
            label="Gilad Gray"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM