[SOLVED] 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

You’re setting your values in the state in a wrong manner. I’ve made some changes to your select handler function which hopefully solves your problem:

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) => {
    console.log(e.target.value);
    switch (e.target.value) {
      case 'first':
        setOption(options[0].value);
        break;
      case 'second':
        setOption(options[1].value);
        break;
      case 'third':
        setOption(options[2].value);
        break;
    }
  };

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

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

export default App;


This Question was asked in StackOverflow by David and Answered by BISWASH BURA It 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?