What is the best way to handle a button when a TimePicker component is invalid?
import * as React from "react";
import dayjs from "dayjs";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { TimePicker } from "@mui/x-date-pickers/TimePicker";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import Button from "@mui/material/Button";
export default function MaterialUIPickers() {
const [value, setValue] = React.useState(new Date());
const [error, setError] = React.useState(false);
const handleChange = (newValue) => {
console.log(newValue);
setValue(newValue);
setError(false);
};
const handleError = () => {
setError(true);
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={3}>
<DesktopDatePicker
label="Date desktop"
inputFormat="MM/DD/YYYY"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<TimePicker
label="Time"
value={value}
onChange={handleChange}
onError={handleError}
renderInput={(params) => <TextField {...params} />}
/>
<Button variant="contained" disabled={error}>
Contained
</Button>
</Stack>
</LocalizationProvider>
);
}
Right now, even if the TimePicker or DesktopDatePicker has an error (for example, change the time manually), you can hit the Save button.
But I'd like the button to be disabled if TimePicker or DesktopDatePicker are invalid.
How can I do it?
I tried using onError so when onError is fired, change the error state to true, but there isn't a good way to set the error state to false once the error is gone.