I have json payload that is passed as a key value pair. I need to populate the data in a TextField select which acts as a drop down. I am able to select the first or second options in the drop down if there is two or more items in the drop down. However, when there is a single item in the drop down it does not get selected even when I click on it.
This is my code below where I set my state as I am using a functional component:
const [departments, setDepartments] = useState([]);
const [selected, setSelected] = useState();
This is code below that checks if the item in the TextField is clicked:
const handleChange = event => {
setSelected(event.currentTarget.id);
};
Also this is my code below that I set the TextField with the data that I receive from the API:
<TextField
fullWidth
label="Select Department"
margin="dense"
name="departments"
onChange={handleChange}
required
select
// eslint-disable-next-line react/jsx-sort-props
SelectProps={{ native: true }}
value={selected}
variant="outlined"
>
{departments.map(option => (
<option
key={option.id}
value={option.id}
>
{option.department}
</option>
))}
</TextField>
Kindly help me resolve this. So I can get to set the first item in the drop down even if it is the only item in the drop down.
you had some error on your code like you used event.currentTarget.id but you should use event.target.value.
However, when there is a single item in the drop down it is not called handleChange when you click on it, because handleChange is onChange event. If you have one item, you cannot change item as there is only one, so onChange event is not fired. Instead, you can add another item like "Please select" then you can select your single item. Please check this example:
import React, {useEffect, useState} from "react";
import TextField from "@material-ui/core/TextField";
function TextFieldDDL() {
const [selected, setSelected] = useState();
const departments=[
{id: -1, department: 'Please Select...'},
{id: 1, department: 'CSE'},
// {id: 2, department: 'BBA'},
// {id: 3, department: 'EEE'}
];
function handleChange(e){
console.log(e.target.value, 'e');
setSelected(e.target.value);
}
return (
<React.Fragment>
<TextField
fullWidth
label="Select Department"
margin="dense"
name="departments"
onChange={handleChange}
required
select
// eslint-disable-next-line react/jsx-sort-props
SelectProps={{native: true}}
value={selected}
variant="outlined"
>
{departments.map(option => (
<option
key={option.id}
value={option.id}
>
{option.department}
</option>
))}
</TextField>
</React.Fragment>
);
}
export default TextFieldDDL;
Update: Add item into the list
const departments = [{id: -1, department: 'Please Select...'}, ...response.data];
setDepartments(departments);