I've been wondering how to set the default value of a Select in React when we use the MenuItem component as options.
First, I get an user list with the following useEffect that returns a list of users (objects with id, firstName and lastName among other attributes)
const [userList, setUserList] = useState([]);
//Get users
useEffect(() => {
userService
.listUsersFromTeamRHandAdmin()
.then((res) => {
setUserList(res)
});
}, [])
const {
setFieldValue
} = useFormikContext();
const handleChange = (e) => {
setFieldValue("user.id", setUserList[e.target.value].id)
}
I have the following Select component, where I would like to have the first user's id of the UserList as a default value, with this user's firstname and lastname displayed.
<Select
name="user"
defaultValue={userList[0].id || ''}
onChange={(e) => handleChange(e)}
style={{
width: "100%",
marginBottom: "1em"
}}
>
{
Object.keys(userList).map((e, keyIndex) => {
return (
<MenuItem key={keyIndex} value={e}>
{userList[e].firstName} {userList[e].lastName}
</MenuItem>
);
})
}
</Select>
Does anyone know how I can do that ?
Edit:
For example, the array of UserList would contain something like:
0: Object { id: 1, firstName: "Britta", lastName: "Perry", … }
1: Object { id: 2, firstName: "Troy", lastName: "Barnes", … }
To have a defaultValue in the MaterialUi Select Component you should provide a defaultValue that exist in your choices, please try this :
import "./styles.css";
import { Select, MenuItem } from "@mui/material";
export default function App() {
const arr = [
{ id: 1, firstName: "Britta", lastName: "Perry" },
{ id: 2, firstName: "Troy", lastName: "Barnes" }
];
return (
<div className="App">
<Select
name="user"
defaultValue={arr[0].firstName + arr[0].lastName || ""}
onChange={(e) => handleChange(e)}
style={{
width: "100%",
marginBottom: "1em"
}}
>
{arr.map((el) => (
<MenuItem key={el.id} value={el.firstName + el.lastName}>
{el.firstName + el.lastName}
</MenuItem>
))}
</Select>
</div>
);
}
As you can see, the defaultValue and the menuItem have the same syntaxe, this a working demo that I've created for this
you can add separator between firstName and lastName but keep the same syntaxe in defaultValue too.