Reputation: 17
I have the following code below that is loaded on a user profile page. Each user has a Planting System. When loading the code below, the application should select the user's respective Plant System. However, this is not happening because I am not able to use the selected option related to the user who loaded the page.
<Input
type="select"
name="planting_system_id"
id="planting_system_id"
value={planting_system_id}
autoComplete="planting_system_id"
className="form-control"
placeholder={apiData ? "Planting System" : "Loading..."}
disabled={apiData ? false : true}
onChange={(ev) => this.onChangeInput("planting_system_id", ev)}
>
<option value="">Select...</option>
{plantingSystemsList.map(ps => (
<option value={ps.id} key={ps.id}>
{ps.description}
</option>
))}
</Input>
And when trying to use the select in option list, there is an error on the part of React that I should use defaultValue or value instead of selected. However, I am not sure how to do this.
Upvotes: 0
Views: 77
Reputation: 378
Did you try setting the selected prop in the option item instead of the input? Something like this:
<option value={ps.id} key={ps.id} selected={ps.id === planting_system_id}>
{ps.description}
</option>
Example:
const {
useState
} = React;
const Example = () => {
const [optionSelected, setOptionSelected] = useState(null);
const optionsList = [{
value: "volvo",
label: "Volvo"
},
{
value: "saab",
label: "Saab"
},
{
value: "audi",
label: "Audi"
},
{
value: "mercedes",
label: "Mercedes"
}
];
return (
<div>
<select name="cars" id="cars"> {
optionsList.map(({
value,
label
}) => (
<option
key = {value}
selected = {optionSelected === value}
value = {value}
>
{label}
</option>
))
} </select>
<button onClick = {
() => {
setOptionSelected("audi");
}
}>
Set Audi as selected
</button>
</div>
);
};
ReactDOM.render( <
Example / > ,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Code sandbox if you prefer: https://codesandbox.io/embed/late-sunset-jglpd?fontsize=14&hidenavigation=1&theme=dark
Upvotes: 1