I am using a date component of material ui, and i have an array that comes from the backend api where in which i have some dates marked as present or absent status, so i want to match that date with mui component's date and reflect background as green color when status is present and red color when status is absent.
import * as React from 'react';
import { useState, useEffect } from 'react';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateCalendar } from '@mui/x-date-pickers/DateCalendar';
import axios from 'axios';
function EmployeeAttendanceCalendar() {
const [attendanceData, setAttendanceData] = useState([]);
const [selectedDate, setSelectedDate] = useState(null);
const base_url = process.env.REACT_APP_BASE_URL;
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
const token = localStorage.getItem('token');
axios
.get(`${base_url}/emp/attendance`, {
headers: {
'Authorization': token,
},
})
.then((response) => {
console.log(response);
// Assuming the response data contains attendance information
setAttendanceData(response.data);
})
.catch((err) => {
console.log(err);
});
};
const customRenderCell = (date, view) => {
const formattedDate = date.toISOString().split('T')[0];
const isSelected = selectedDate && formattedDate === selectedDate.toISOString().split('T')[0];
const attendanceEntry = attendanceData.find((entry) => entry.date.split('T')[0] === formattedDate);
return (
<div
style={{
backgroundColor: isSelected
? 'blue'
: attendanceEntry
? attendanceEntry.presentStatus === 'present'
? 'green'
: attendanceEntry.presentStatus === 'halfday'
? 'orange'
: 'red'
: 'transparent',
}}
onClick={() => handleDateClick(date)}
>
{date.getDate()}
</div>
);
};
const handleDateClick = (date) => {
setSelectedDate(date);
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DateCalendar customRenderCell={customRenderCell} />
</LocalizationProvider>
);
}