I have a select component:
<Select}>
{data &&
data.map((survey) => (
<Option key={survey.id} value={survey.id}>
{survey.name}
</Option>
))
}
</Select>
The data array is coming from an API fetch using axios, which is then saved in the state data:
const [data, setData] = useState([]);
How do I grab the selected value and display it?
I tried adding an onChange
handler to the component and save the e.target.value
in a separate piece of state:
onChange={e => setInput(e?.target?.value)}
However, I'm getting an error that value
is undefined
. I suspect it's because the data hasn't loaded yet.
How do you get the selected value from the options when the options are coming from an API? (i.e., dynamic dropdown)
Try like this :
const [data, setData] = useState([]);
const handleChange = (e) => {
console.log(e.target.value);
setData(e.target.value);
};
<select onChange={handleChange}>
{dataArr &&
dataArr.map((survey) => (
<option key={survey.id} value={survey.id}>
{survey.name}
</option>
))}
</select>
Example : Example
You need to define a new state and set it in onChange
handler to show the selected data at somewhere else.
Define it as:
const [selectedValue,setSelectedValue] = useState()
Then, set it:
const handleChange = (e) => {
setSelectedValue(e.target.value)
}
it is now available to use anywhere in this component.
Here is an example:
import React, { useState, useEffect } from 'react';
export default function App() {
const [data, setData] = useState([]);
const [selectedValue,setSelectedValue] = useState()
// this useEffect is just a simulator for api response, you do not need this useEffect,
// instead just call your api and set the data with your awaited response
useEffect(()=>{
setTimeout(()=> {
setData([
{ name: 'first Option', id: 'ID of first option'},
{ name: 'Second Option', id: 'ID of second option' }
])
},[2000])
},[])
const handleChange = (e) => {
console.log(e.target.value); // maybe print the value to check
setSelectedValue(e.target.value)
}
return (<div>
<select onChange={handleChange}>
{data &&
data.map((survey) => (
<option key={survey.id} value={survey.id}>
{survey.name}
</option>
))}
</select>
{selectedValue ? <div>Selected value: {selectedValue} </div> : ''}
</div>
);
}
Can you confirm that the value attribute on the option tag is properly set and it has the value you want it to have.