reactjstypescriptmaterial-uimui-x-date-picker

How to highlight some specific days?


I want to use mui-x-date-pickers to highlight some specific days from a Date array (using new Date), like a green filled circle around the day number. How can I achieve that?

This is my current code:

<DatePicker
            label="Date du jour à visualiser"
            openTo="day"
            views={["day", "month", "year"]}
            value={value}
            format="dd.MM.yyyy"
/>

Thanks in advance for your answers.


Solution

  • I got it to work. Here is my code:

    import { isSameDay } from "date-fns";
    import { PickersDay, PickersDayProps } from "@mui/x-date-pickers";
    import { DatePicker } from "@mui/x-date-pickers/DatePicker";
    import React from "react";
    
    const highlightedDays: Array<Date> = [new Date("1970-01-01")];
    
    const CustomDay = (props: PickersDayProps<Date>) => {
        console.log(JSON.stringify(props));
        const matchedStyles = highlightedDays.reduce((a, v) => {
            const date = new Date(props.day);
            return isSameDay(date, v) ? { backgroundColor: "#004b95" } : a;
        }, {});
    
        return <PickersDay {...props} sx={{ ...matchedStyles }} />;
    };
    
    return (<DatePicker
        label="Date du jour à visualiser"
        openTo="day"
        views={["day", "month", "year"]}
        value={value}
        format="dd.MM.yyyy"
        slots={{ day: CustomDay }}
    />);
    

    Add some dates in the array, then you're good to go!