Soy nuevo para reaccionar js. He escrito un código para seleccionar la opción para la pregunta particular. Solo quiero mostrar la opción seleccionada junto al menú desplegable. Pero cuando seleccioné la opción, muestra el mismo valor para todas las preguntas. ¿Alguien podría ayudarme a resolver esto?
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 */} <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.pngDebe crear diferentes variables de estado para ambos campos. A partir de ahora, ambos valores de campo se almacenan en el mismo estado.
Debe almacenar el valor relacionado con cada select por separado, para lograr su objetivo, puede definir diferentes estados, o puede almacenar valores en un objeto en lugar de una cadena, como esta:
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 */} <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>