DEV Community

TharunKumar
TharunKumar

Posted on

Calendar events using React MUI

`import { useState } from "react";
import FullCalendar, { formatDate } from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import listPlugin from "@fullcalendar/list";
import {
Box,
List,
ListItem,
ListItemText,
Typography,
useTheme,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
Button,
} from "@mui/material";
import Header from "../../components/Header";
import { tokens } from "../../theme";

const Calendar = () => {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const [currentEvents, setCurrentEvents] = useState([]);
const [isOpen, setIsOpen] = useState(false);
const [newEventTitle, setNewEventTitle] = useState("");
const [selectedDate, setSelectedDate] = useState(null);
const [deletingEventId, setDeletingEventId] = useState(null); // State to track the event being deleted

const handleDateClick = (selected) => {
setSelectedDate(selected.date);
setNewEventTitle("");
setIsOpen(true);
};

const handleEventClick = (selected) => {
setDeletingEventId(selected.event.id); // Set the event ID to be deleted
setIsOpen(true);
};

const handleDeleteEvent = () => {
// Filter out the event with the deletingEventId
setCurrentEvents(currentEvents.filter((event) => event.id !== deletingEventId));
setIsOpen(false); // Close the confirmation dialog
setDeletingEventId(null); // Reset deletingEventId
};

const handleAddEvent = () => {
if (!selectedDate || !newEventTitle) return;

const newEvent = {
  id: `${new Date().toISOString()}-${newEventTitle}`,
  title: newEventTitle,
  start: selectedDate,
  allDay: true, // Assuming all events are all-day for simplicity
};

setCurrentEvents([...currentEvents, newEvent]);
setIsOpen(false);
Enter fullscreen mode Exit fullscreen mode

};

return (

  <Box display="flex" justifyContent="space-between">
    {/* CALENDAR SIDEBAR */}
    <Box
      flex="1 1 20%"
      backgroundColor={colors.primary[400]}
      p="15px"
      borderRadius="4px"
    >
      <Typography variant="h5">Events</Typography>
      <List>
        {currentEvents.map((event) => (
          <ListItem
            key={event.id}
            sx={{
              backgroundColor: colors.greenAccent[500],
              margin: "10px 0",
              borderRadius: "2px",
            }}
          >
            <ListItemText
              primary={event.title}
              secondary={
                <Typography>
                  {formatDate(event.start, {
                    year: "numeric",
                    month: "short",
                    day: "numeric",
                  })}
                </Typography>
              }
            />
            <Button
              variant="outlined"
              color="secondary"
              onClick={() => handleEventClick({ event })}
            >
              Delete
            </Button>
          </ListItem>
        ))}
      </List>
    </Box>

    {/* CALENDAR */}
    <Box flex="1 1 100%" ml="15px">
      <FullCalendar
        height="75vh"
        plugins={[
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin,
          listPlugin,
        ]}
        headerToolbar={{
          left: "prev,next today",
          center: "title",
          right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth",
        }}
        initialView="dayGridMonth"
        editable={true}
        selectable={true}
        selectMirror={true}
        dayMaxEvents={true}
        events={currentEvents} // Pass currentEvents to FullCalendar
        eventClick={handleEventClick}
        dateClick={handleDateClick}
        eventDidMount={(info) => {
          info.el.style.backgroundColor = colors.greenAccent[500];
        }}
      />
    </Box>
  </Box>

  {/* DELETE EVENT DIALOG */}
  <Dialog open={isOpen} onClose={() => setIsOpen(false)}>
    <DialogTitle>Confirm Delete Event</DialogTitle>
    <DialogContent>
      <Typography>
        Are you sure you want to delete this event?
      </Typography>
    </DialogContent>
    <DialogActions>
      <Button onClick={() => setIsOpen(false)} color="primary">
        Cancel
      </Button>
      <Button onClick={handleDeleteEvent} color="secondary">
        Delete
      </Button>
    </DialogActions>
  </Dialog>

  {/* ADD EVENT DIALOG */}
  <Dialog open={isOpen && !deletingEventId} onClose={() => setIsOpen(false)}>
    <Box p="20px">
      <Typography variant="h6" gutterBottom>
        Add New Event
      </Typography>
      <TextField
        label="Event Title"
        value={newEventTitle}
        onChange={(e) => setNewEventTitle(e.target.value)}
        fullWidth
        variant="outlined"
        margin="normal"
      />
      <Button
        variant="contained"
        color="primary"
        onClick={handleAddEvent}
      >
        Add Event
      </Button>
    </Box>
  </Dialog>
</Box>
Enter fullscreen mode Exit fullscreen mode

);
};

export default Calendar;
`

Top comments (0)