Have anyone added events to MUI DatePicker
? Or someone know to change background of selected day? For example change color of the selected day? Or add a birthday to selected day?
My code:
import React from "react";
import TextField from "@mui/material/TextField";
import AdapterDateFns from "@mui/lab/AdapterDateFns";
import LocalizationProvider from "@mui/lab/LocalizationProvider";
import StaticDatePicker from "@mui/lab/StaticDatePicker";
import isWeekend from "date-fns/isWeekend";
export default function DatePicker() {
const [value, setValue] = React.useState<Date | null>(new Date());
console.log(value);
return (
<div>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<StaticDatePicker<Date>
orientation="portrait"
openTo="day"
value={value}
shouldDisableDate={isWeekend}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</div>
);
}
You can create a custom PickersDay
component and override the selected day background color like this:
import DatePicker from "@mui/lab/DatePicker";
import PickersDay, {
PickersDayProps,
pickersDayClasses
} from "@mui/lab/PickersDay";
const renderWeekPickerDay = (
date: Date,
selectedDates: Array<Date | null>,
pickersDayProps: PickersDayProps<Date>
) => {
return (
<PickersDay
{...pickersDayProps}
sx={{
[`&&.${pickersDayClasses.selected}`]: {
backgroundColor: "green"
}
}}
/>
);
};
Then override the renderDay
callback in DatePicker
:
<DatePicker
renderDay={renderWeekPickerDay}
{...}
/>
Edit: If you want to highlight multiple days with different styles:
type HighlightedDay = {
date: Date;
styles: React.CSSProperties;
};
const highlightedDays: HighlightedDay[] = [
{
date: birthday,
styles: { color: "red" }
},
{
date: addDays(new Date(), 6),
styles: { /* ... */ }
},
{
date: addDays(new Date(), 9),
styles: { /* ... */ }
},
{
date: addDays(new Date(), 12),
styles: { /* ... */ }
}
];
const renderWeekPickerDay = (
date: Date,
selectedDates: Array<Date | null>,
pickersDayProps: PickersDayProps<Date>
) => {
const matchedStyles = highlightedDays.reduce((a, v) => {
return isSameDay(date, v.date) ? v.styles : a;
}, {});
return (
<PickersDay
{...pickersDayProps}
sx={{
...matchedStyles,
[`&&.${pickersDayClasses.selected}`]: {
backgroundColor: "green"
}
}}
/>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With