How to get the "value" of a select in Reactjs

Asked

Viewed 82 times

-1

I made the following code, I would like to take the value of the "value" of the select, (the car color and show in the H3 tag when the button is triggered) I tried to use .target.value but without success

Code in the codesandbox

import React, { useState } from "react";

export default function Resultado() {
  const [valor, setValor] = useState("Cor");

  return (
    <section>
      <div>
        <h3>Cor do Carro</h3>
        <select>
          <option value="Vermelho" selected>
            Uno
          </option>
          <option value="Branca">Parati</option>
          <option value="Azul">Fusca</option>
        </select>
        <button
          onClick={(event) => {
            setValor(event.target.value);
          }}
        >
          Enviar Resultado
        </button>
      </div>

      <h3>A cor do carro é: {valor}</h3>
    </section>
  );
}
  • 2

    This answer will help you. Basically what should be done is to move this (event) => {setValor(event.target.value); } to the select at the event onChange. Would be +- like this: <select onChange={(event) => {setValor(event.target.value);}>

1 answer

0

Hello, you can get the desired result by modifying your code to the following:

<select onChange={(e) => setValor(e.target.value)}>
          <option value="Vermelho" selected>
            Uno
          </option>
          <option value="Branca">Parati</option>
          <option value="Azul">Fusca</option>
        </select>

Each time a different item is selected it will update the value of the hook.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.