React select option with multiple object values

Issue

This Content is from Stack Overflow. Question asked by David

I’m trying to save multiple values in one select and saving it in useState to use it again somewhere else. but it’s not working I only get undefined values in my console.log .

here is the code:

import * as React from "react";
function App() {
  const [option, setOption] = React.useState({ width: 0, height: 0 });

  const options = [
    {
      label: "first",
      value: { width: 10, height: 10 },
    },
    {
      label: "second",
      value: { width: 20, height: 20 },
    },
    {
      label: "third",
      value: { width: 30, height: 30 },
    },
  ];
  const selectHandler = (e) => {
    setOption(e.target.value);
  };

  console.log(option.width);
  console.log(option.height);

  return (
    <div className="App">
      <h1>Test!</h1>
      <select value={options.value} onChange={selectHandler}>
        {options.map((option) => (
          <option key={option.label}>{option.label}</option>
        ))}
      </select>
      <p></p>
    </div>
  );
}

export default App;

I don’t know if it’s even possible…
thanks in advance!



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?