import React, { useState } from "react";
import { Button, Stack, TextField, Typography, useTheme } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
const AgeCalculator: React.FC<{}> = () => {
const theme = useTheme();
const [date, setDate] = useState<Dayjs | null>(dayjs());
const [age, setAge] = useState<string>("");
const [error, setError] = useState<string>("");
const handleChange = (newValue: Dayjs | null) => {
if (newValue.isAfter(dayjs())) {
setError("Date cannot be in future");
setAge("");
setDate(newValue);
return;
}
setDate(newValue);
setError("");
};
const handleClick = () => {
console.log("Button Clicked");
};
return (
<Stack spacing={3} mx={2} my={5}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="Date of Birth (DD-MMM-YYYY)"
inputFormat="DD-MMM-YYYY"
value={date}
onChange={handleChange}
disableMaskedInput={true}
renderInput={(params) => <TextField {...params} disabled={true} />}
/>
</LocalizationProvider>
<Button
sx={{ mt: 1, mr: 1, boxShadow: 2 }}
type="submit"
variant="outlined"
onClick={handleClick}
>
Calculate
</Button>
{age.length !== 0 && (
<Typography
variant="h6"
sx={{
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
Your age is {age}.
</Typography>
)}
{error.length !== 0 && (
<Typography
variant="h6"
sx={{
overflow: "hidden",
textOverflow: "ellipsis",
}}
style={{ color: theme.palette.error.main }}
>
{error}
</Typography>
)}
</Stack>
);
};
export default AgeCalculator;