Reputation: 343
I have a select in a functional component and I cannot get the value when I select an option. I could only find solution for a class based component. I thought useState would do the trick but I am missing something...
const ClientChoice = (props) => {
const [selectedClient,setSelectedClient] = useState([]);
function handleSelectChange(event) {
setSelectedClient(event.target.value);
}
return (
<select onChange={handleSelectChange}>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
)
}
The target is null
.
Upvotes: 3
Views: 18510
Reputation: 996
You are not providing the value to select
and change default value for selectedClient
:
const ClientChoice = (props) => {
const [selectedClient,setSelectedClient] = useState("one"); //default value
function handleSelectChange(event) {
setSelectedClient(event.target.value);
}
return (
<select value={selectedClient} onChange={handleSelectChange}> //set value here
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
)
}
Upvotes: 3
Reputation: 66
The solution for FC: add value to your select
const ClientChoice = (props) => {
const [selectedClient,setSelectedClient] = useState([]);
function handleSelectChange(event) {
setSelectedClient(event.target.value);
}
return (
<select value={selectedClient} onChange={handleSelectChange}> //set value here
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
)
}
Upvotes: 3