简体   繁体   中英

Select Dropdown not Passing Selected Values to Array in React

I am building a dropdown menu in React using a select dropdown.

or some reason, my selected value is not passing, it is passing the entire array instead of the value I selected on the dropdown.

What am I doing wrong here and how can I pass the value that I selected via dropdown?

Dropdown Code in React

  <select
                className='add-cap-select'
                onChange={(value) => handleChangeForm('agent', value)}
              >
                {agents.map((agent) => (
                  <option id='agent' key={agent} value={form.agent}>
                    {agent}
                  </option>
                ))}
              </select>

      /**
   * Handles when the user changes any regular form entry
   * @param {String} prop
   * @param {String} value
   */
  const handleChangeForm = (prop, value) => {
    setForm({
      ...form,
      [prop]: value
    })
  }

Here is my simple solution to do this

import React, {useState} from 'react';

export function App(props) {
  const [agent, setAgent] = useState({
    agent:'',
  });
  const handleChangeForm = event =>{
    console.log(event.target.name, event.target.value)
    setAgent({...agent,[event.target.name]:event.target.value})
  }

  return (
    <select
                className='add-cap-select'
                name="agent"
                onChange={(event) => handleChangeForm(event)}
              >
               <option value="one">one</option>
               <option value="two">two</option>
               <option value="three">three</option>
              </select>
  );
}

you are passing agent and value both in handleFormChange, instead of this you can put the name in select, and from the event, you can get the name as well as value, here you are directly passing value which is event actually if you want to do in your solution then you can do like this -> value.target.value

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