- To ensure the Date Picker works as expected, set the initial value of the date to null in your state.
- You can also utilize the emptyLabel property to specify a custom placeholder text when the date is null.
View the demo on codesandbox here
code
function App() {
const [dob, setDob] = useState(null); //<--- pass initial value as null
const handleDateChange = date => {
setDob(date);
};
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker
fullWidth
onChange={handleDateChange}
value={dob}
label="Date of Birth"
format="dd / MM / yyyy"
margin="normal"
maxDate={new Date()}
emptyLabel="custom label" //<--- custom placeholder when date is null
// InputProps={{ className: css.datepicker }}
/>
</MuiPickersUtilsProvider>
);
}
Edit: responding to follow-up questions from comments.
- Hide the floating label when the date is null - Set the label value when
dob
has a value
label={dob && "Date of Birth"}
- Style the Empty label - Utilize
makeStyles
and InputProps
const useStyles = makeStyles(theme => ({
datepicker: {
margin: "2px 0px 2px 0px",
height: "60px",
// width: 'fit-content',
padding: "20px 15px 10px",
borderBottom: "2px solid blue",
backgroundColor: "#fff",
color: "#2c2c2c",
width: 300,
fontWeight: 600
}
}));
function App() {
const [dob, setDob] = useState(null); //<--- pass initial value as null
const classes = useStyles();
const handleDateChange = date => {
setDob(date);
};
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker
fullWidth
onChange={handleDateChange}
value={dob}
label={dob && "Date of Birth"}
format="dd / MM / yyyy"
margin="normal"
maxDate={new Date()}
emptyLabel="custom label" //<--- custom placeholder when date is null
InputProps={{ className: !dob ? classes.datepicker : null }} //<----apply style when no date selected
/>
</MuiPickersUtilsProvider>
);
}
The codesandbox demo has been updated to incorporate all the modifications mentioned above.