Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
How to bind the selected option from the drop down to a reactjs state property in functional component and show it to side of the dropdown

I am new to react js. I have written a code for selecting the option for the perticular question. I just want to display the selected option next to the drop down. But when I selected the option it is displaying the same value for all the questions. could anyone please help me in resolving this.

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [select, setSelect] = useState("");

  const optionchanged = (e) => {
    setSelect(e.target.value);
  };

  const questions = [
    {
      id: 1,
      qst: "which country you are from",
      options: ["select", "USA", "UK", "Australia", "India"]
    },
    {
      id: 2,
      qst: "What is your country code",
      options: ["select", "+1", "+44", "+61", "+91"]
    }
  ];
  return (
    <div className="App" style={{ "text-align": "left" }}>
      {questions.map((quest) => (
        <div>
          {/* displaying the question */}
          <p>
            {" "}
            {quest.id}. {quest.qst}
          </p>
          {/* showing the options */}
          <select onChange={optionchanged}>
            {quest.options.map((option) => (
              <>
                <option> {option}</option>
              </>
            ))}
          </select>
          {/* selected option showing next to the dropdown */}
          &nbsp;&nbsp;
          <span style={{ color: "blue" }}>{select} </span>
        </div>
      ))}
    </div>
  );
}



here is the output I got , here the second question also giving the same option without selecting it.
 

  [1]: https://i.stack.imgur.com/tFyu8.png
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to create different state variables for both fields. As of now both the field values are stored to the same state.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need store the value related to every select separately, to achieve your goal, you can define different states, or you can store values in an object instead of string, like this:

function App() {
  const [select, setSelect] = React.useState({});

  const optionchanged = (e, id) => {
    setSelect( select => ({ ...select, [id]: e.target.value })  );
  };

  const questions = [
    {
      id: 1,
      qst: "which country you are from",
      options: ["select", "USA", "UK", "Australia", "India"]
    },
    {
      id: 2,
      qst: "What is your country code",
      options: ["select", "+1", "+44", "+61", "+91"]
    }
  ];
        
  return (
    <div className="App" style={{ "text-align": "left" }}>
      {questions.map((quest) => (
        <div>
          {/* displaying the question */}
          <p>
            {" "}
            {quest.id}. {quest.qst}
          </p>
          {/* showing the options */}
          <select onChange={e => optionchanged(e, quest.id)}>
            {quest.options.map((option) => (
                <option> {option}</option>
            ))}
          </select>
          {/* selected option showing next to the dropdown */}
          &nbsp;&nbsp;
          <span style={{ color: "blue" }}>{select[quest.id]} </span>
        </div>
      ))}
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda