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 */}
<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
You need to create different state variables for both fields. As of now both the field values are stored to the same state.
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 */}
<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>