Select Component (dropdown) of Material Ui is not showing its label
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={role}
label="Role"
size='small'
sx={{ width: '90%', marginBottom: '1rem' }}
>
<MenuItem value= 'MVD'>MVD</MenuItem>
<MenuItem value= 'Police'>Police</MenuItem>
<MenuItem value= 'Coperation'>Coperation</MenuItem>
</Select>
I'm expecting a result like the one shown above
If you can help me resolve this simple bug, I will greatly appreciate it
CodePudding user response:
Hi @Guit Adharsh,
There are a lot of things need you to note. You need to change the value of the Role
state variable when a MenuItem is selected,
function App() {
const [Role, setRole] = useState("MVD");
return (
<>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={Role} // here we are using the Role state.
label="Role"
size="small"
onChange={(event) => setRole(event.target.value)} //update the Role state
sx={{ width: "90%", marginBottom: "1rem" }}
>
<MenuItem value="MVD">MVD</MenuItem>
<MenuItem value="Police">Police</MenuItem>
<MenuItem value="Coperation">Coperation</MenuItem>
</Select>
</>
);
}
onchange event uses the setRole
function to update the Role state with the new value that will select.
Here is the Demo:- codesandbox
CodePudding user response:
import * as React from "react";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import { makeStyles } from "@mui/styles";
const usePlaceholderStyles = makeStyles((theme) => ({
placeholder: { color: "#a3a3a3" }
}));
const Placeholder = ({ children }) => {
const classes = usePlaceholderStyles();
return <div className={classes.placeholder}>{children}</div>;
};
export default function BasicSelect() {
const [role, setRole] = React.useState("");
return (
<Box sx={{ minWidth: 120 }}>
<FormControl fullWidth>
<Select
fullWidth
size="small"
value={role}
displayEmpty
onChange={(event) => setRole(event.target.value)}
renderValue={
role !== "" ? undefined : () => <Placeholder>Role</Placeholder>
}
>
<MenuItem value="MVD">MVD</MenuItem>
<MenuItem value="Police">Police</MenuItem>
<MenuItem value="Coperation">Coperation</MenuItem>
</Select>
</FormControl>
</Box>
);
}