1

My goal is to collect all the values from the selected option into a state. How to do it correctly? I thought about how to refer to the attributes of the selected option, but I did not succeed. I have the following State

  const [search, setSearch] = useState({
    phone: "",
    mark: "",
    model: "",
    name: "",
  })

Here is my onChange function

  const onSearchChange = (e) => {
    const { name, value } = e.target
    setState((prevState) => ({
      ...prevState,
      [name]: value,
    }))
  }

And there is a Select mapping values from an object. So such values as {it.name}, {it.mark}, {it.model} and so on I want to collect in the search state

<select
  className="block appearance-none w-full"
  value={search}
  name="search"
  id="searchBlock"
  onChange={onSearchChange}>
  {customerList.map((it) => {
    return (
      <option
       value={it.name}
       phone={it.phone}>
        {it.name}, {it.mark} {it.model} {it.regnumber}, {it.phone} 
      </option>
    )
  })}
</select>

2 Answers 2

2

I think you need something like:


function SelectApp() {
  const [search, setSearch] = React.useState(0);
  const onSearchChange = (e) => {
    const { value } = e.target;
    setSearch(value);
  };
  const customerList = [
    { name: "John", model: "x", regnumber: 23, phone: "+145623455" },
    { name: "Niil", model: "box", regnumber: 44, phone: "+185823499" },
    { name: "Jerry", model: "box", regnumber: 44, phone: "+188823499" }
  ];
  return (
    <div className="App">
      <select
        className="block appearance-none w-full"
        defaultValue={customerList[search]}
        name="search"
        id="searchBlock"
        onChange={onSearchChange}
      >
        {customerList.map((it, key) => {
          return (
            <option value={key}>
              {it.name}, {it.mark} {it.model} {it.regnumber}, {it.phone}
            </option>
          );
        })}
      </select>
    </div>
  );
}

So you can get the values from the list on the key changes

Sign up to request clarification or add additional context in comments.

Comments

0

If you will create an object before to set on the state, so it would be like the following example...

 const onSearchChange = (e) => {
    const { name, value } = e.target
    let newComboBoxValue = {}

    newComboBoxValue[name] = newComboBoxValue[value];
    setState((prevState) => ({
      ...prevState,
      newComboBoxValue
    }))
  }

Good luck!!

CLC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.