Reputation: 861
Code:
const [frequency, setFrequency] = useState({});
function handleSelect(event) {
const target = event.target;
const value = target.value;
const name = target.name;
setFrequency({
...frequency,
[name]: value
})
}
<FormGroup>
<Label for="exampleSelect">Select</Label>
<Input type="select" name="select" id="exampleSelect" onChange= {handleSelect} >
// I tried the below, But it does not seem to work
<Input type="select" name="frequency" id="frequency" value={frequency.frequency}>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</Input>
</FormGroup>
When I select the value it renders in the input but when I want to set the selected value.
Meaning, I want to set the value such that when I load it should start from a selected value not from 1
.
So how can I set the value?
I can setState
by calling some select function. But in input tag I just want a value any value so when I refresh dropdown should show xyx...1,2,3,4
.
Upvotes: 1
Views: 3116
Reputation: 19813
If you write value="xyx"
, the value of select
will always be xyz
no matter what option you select.
So, instead of that you can provide value
from react state and a handleChange
function to change the value on select.
If you want to select the "first option" i.e. xyz
at start, you can initialize the state with xyz
:
export default function App() {
const [frequency, setFrequency] = useState({ frequency: "xyz" });
function handleSelect(e) {
setFrequency((prev) => ({
...prev,
[e.target.name]: e.target.value,
}))
}
return (
<>
{JSON.stringify(frequency)}
<FormGroup>
<Label for="exampleSelect">Select</Label>
<Input
type="select"
name="frequency"
id="frequency"
value={frequency.frequency}
onChange={handleSelect}
>
<option>xyz</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</Input>
</FormGroup>
</>
);
}
Here is a demo
Upvotes: 2