Estou enfrentando um problema com uma atividade que estou realizando relacionada a uma escala mensal. Preciso integrar um componente de calendário do Material UI para selecionar múltiplas datas durante o mês. Já tenho um componente pronto para essa função, que exibe o calendário na tela. No entanto, ao tentar selecionar uma data, a tela fica em branco e no console aparece um erro indicando um loop infinito de renderizações. O erro específico é relatado no componente <ForwardRef(StaticDatePicker)>.
Segue o código do componente:
import * as React from "react";
import { styled } from "@mui/material/styles";
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 PickersDay from "@mui/lab/PickersDay";
import startOfDay from "date-fns/startOfDay";
const CustomPickersDay = styled(PickersDay, {
shouldForwardProp: (prop) => prop !== "selected"
})(({ theme, selected }) => ({
...(selected && {
backgroundColor: theme.palette.primary.main,
color: theme.palette.common.white,
"&:hover, &:focus": {
backgroundColor: theme.palette.primary.dark
},
borderTopLeftRadius: "50%",
borderBottomLeftRadius: "50%",
borderTopRightRadius: "50%",
borderBottomRightRadius: "50%"
})
}));
export default function MultiDatePicker() {
const [values, setValues] = React.useState([]);
const findDate = (dates, date) => {
const dateTime = date.getTime();
return dates.find((item) => item.getTime() === dateTime);
};
const findIndexDate = (dates, date) => {
const dateTime = date.getTime();
return dates.findIndex((item) => item.getTime() === dateTime);
};
const renderPickerDay = (date, selectedDates, pickersDayProps) => {
if (!values) {
return <PickersDay {...pickersDayProps} />;
}
const selected = findDate(values, date);
return (
<CustomPickersDay
{...pickersDayProps}
disableMargin
selected={selected}
/>
);
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<StaticDatePicker
displayStaticWrapperAs="desktop"
label="Week picker"
value={values}
onChange={(newValue) => {
//copying the values array
const array = [...values];
const date = startOfDay(newValue);
const index = findIndexDate(array, date);
if (index >= 0) {
array.splice(index, 1);
} else {
array.push(date);
}
setValues(array);
}}
renderDay={renderPickerDay}
renderInput={(params) => <TextField {...params} />}
inputFormat="'Week of' MMM d"
/>
</LocalizationProvider>
);
}