HaKePlan
HaKePlan

Reputation: 65

Get value of <select> element with React.useState in Nextjs

I am facing a problem in Nextjs with the useState function from React.

I have an element, with several in itself. Now, if I select e useState should set a variable with the selected 's value.

const [value, setValue] = useState('')

...

function logValue() {
  console.log(value)
}

return (
<div>
  <select onChange={(e) => {setValue(e.target.value)}>
    <option value="a">a</option>
    <option selected value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
  </select>

  <button onClick={logValue}>submit</button>
</div>
)

My problem is now, that the first time I make a change in the select field, setValue sets the value from before the change.

When I load the page and change the selected to "a", logValue prints nothing. Then I change the value to "d", logValue prints "a". Then I change the value to "c", logValue prints "b". etc...

How can i make this work, that when I change the select field to "a" logValue prints "a"?

Upvotes: 2

Views: 24636

Answers (1)

Danila
Danila

Reputation: 18516

If you check the console you should be able to see a Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>

So you need to do something like that instead:

export default function App() {
  const [value, setValue] = useState("b");

  function logValue() {
    console.log(value);
  }

  return (
    <div>
      <select
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
      >
        <option value="a">a</option>
        <option value="b">b</option>
        <option value="c">c</option>
        <option value="d">d</option>
      </select>

      <button onClick={logValue}>submit</button>
    </div>
  );
}

Upvotes: 11

Related Questions