简体   繁体   中英

How to get id of selected option in react js

I have created a very simple select box.

<FormGroup>
  <label for='category' className='label'>Category</label>
  <select ref="categoryName">
    {categoriesList}
  </select>
</FormGroup>

and

let categoriesList = categories.map(category =>
  <option id={category.id}>
      {category.type}
   </option>
 )

I'm trying to figure out how I can get the value of 'id' attribute of the option that's selected in the dropdown, I want to use this value for some further processing. please advise. thanks

Using React, you don't need to do this with refs per se, you do have the state.

Take a look at this example:

  const [selectedItem, setSelectedItem] = useState()

  const handleSelect = (event) => {
    setSelectedItem(event.target.value)
  }

  console.log(selectedItem) // Your Selected Option

  return (
    <FormGroup>
      <label htmlFor="category" className="label">
        Category
      </label>
      <select onChange={handleSelect}>{categoriesList}</select>
    </FormGroup>
  )

I am utilizing React's useState module here. It is how we manage state in the newer versions of React. You might be more familiar with this.setState , where the example would be something more like this:

constructor() {
    super()

    this.state = {
      selectedValue: '',
    }
  }

  handleSelect = (event) => {
    this.setState({
      selectedValue: event.target.value,
    })
  }

  console.log(this.state.selectedValue) // Your selected value

  render() {
    return (
      <FormGroup>
        <label htmlFor="category" className="label">
          Category
        </label>
        <select onChange={handleSelect}>{categoriesList}</select>
      </FormGroup>
    )
  }

Keep in mind that I don't see the full file where your code is, so I don't know if your component is made using Classes, like:

Class App extends React.Component or const App = () => {}

Depending on this definition of your component, you should decide which method to use. If it is Class, use the 2nd options, if it is not, use the 1st one.

As for perserving the id , i Would modify your list of selects like this:

let categoriesList = categories.map(category =>
  <option value={category.id} id={category.id}>
      {category.type}
   </option>
 )

this way, the saved state will have category.id and you will be able to further process with it.

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option.

onChangeHandler = (e) => {
  const index = e.target.selectedIndex;
  const el = e.target.childNodes[index]
  const option =  el.getAttribute('id');  
}

<FormGroup>
  <label for='category' className='label'>Category</label>
  <select onChange={onChangeHandler}>
      {categories.map(category =>
          <option id={category.id}>
             {category.type}
          </option>
      )}
  </select>
</FormGroup>

Ideally you should try and avoid getting state from the DOM.

React works really well if you control state, and leave React to render your state.

Below is a simple example, basically all I do is store the state index into an array,. And when I update this, the React view will update accordingly. How you store state is then totally up to you, and not the DOM.

 const {useState} = React; const lookup = [ {id: 1, value: 'one'}, {id: 2, value: 'two'}, {id: 3, value: 'three'} ]; function List() { const [selected, setSelected] = useState(-1); const value = selected;== -1 && lookup[selected]. return <div> <select onChange={(e) => setSelected(e.target.value)} value={selected}> <option>Please Selected an option</option> {lookup,map((m. ix) => { return <option key={m.id} value={ix} > {m;value} </option> })}: </select> {value && <div style={{marginTop. "2rem"}}> You selected ID <span>{value.id}</span> value <span>{value;value}</span> </div>} </div>. } ReactDOM,render(<List/>. document;querySelector('#mount'));
 body, select, option { font-size: 20px; } select, option { padding: 0.5rem; } body { padding: 2rem; } span { font-weight: bold; margin: 1em; background-color: yellow; border: 1px solid black; padding: 1em 1.5rem; border-radius: 50%; }
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="mount"/>

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