I have a Textbox where I set array items to the textbox and I use it as a drop down. My code works and I am able to see the items in the drop down, however when i click on any other item apart from the first item I get the error groups.map is not a function. I set array from the API to my groups and then I try to map the items that I need into the textbox. Please see my code below and assist me to fix it.
I set my state to an empty array here
const [groups, setGroups] = useState([]); const handleChange = event => { setGroups({ ...groups, [event.target.name]: event.target.value }); };
I handle my API call here
axios .post('http://', formData, config) .then((response) => { console.log(response.data) setGroups(response.data); }) .catch((error) => { console.log(error.response); }); }, []);
I render with my data to show in the drop down here
<TextField fullWidth label="Select Group" margin="dense" name="groups" onChange={handleChange} required select // eslint-disable-next-line react/jsx-sort-props SelectProps={{ native: true }} value={groups.name} variant="outlined" > {groups.map(option => ( <option key={option.id} > {option.name} </option> ))} </TextField>
Advertisement
Answer
Try adding a new state variable to store the selected group.
const [selected, setSelected] = useState();
Your handleChange function will become something like
const handleChange = event => { setSelected(event.target.value); };
And your TextField component will have it’s value changed to match the corresponding state variable:
<TextField fullWidth label="Select Group" margin="dense" name="groups" onChange={handleChange} required select // eslint-disable-next-line react/jsx-sort-props SelectProps={{ native: true }} value={selected} variant="outlined" > {groups.map(option => ( <option key={option.id} > {option.name} </option> ))} </TextField>