Context menu in React Schedule component

30 Jan 202624 minutes to read

You can display a context menu on scheduler work cells and appointments by using the ContextMenu control manually in the application. In the following code example, the context menu is added in the example and its target is set to the Scheduler component.

On scheduler cells, you can display menu items such as New Event, New Recurring Event, and Today. For appointments, you can display options such as Edit Event and Delete Event. Use the openEditor method of the Scheduler to open the default event window for creating or editing appointments.

The deletion of appointments can be done by using the deleteEvent public method. Also, the selectedDate property can be used to navigate between different dates.

You can also display custom menu options on scheduler cells and appointments. Context menu will open on tap-hold in responsive mode.

import { useRef, useState, useMemo, useEffect } from 'react';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { closest, isNullOrUndefined, remove, removeClass } from '@syncfusion/ej2-base';
import { Query, DataManager } from '@syncfusion/ej2-data';
import {
  ScheduleComponent, ViewsDirective, ViewDirective,
  Day, Week, WorkWeek, Month, Agenda, Inject
} from '@syncfusion/ej2-react-schedule';
import { ContextMenuComponent } from '@syncfusion/ej2-react-navigations';
import { scheduleData } from './datasource';


const App = () => {
  const scheduleObj = useRef(null);
  const menuObj = useRef(null);
  const [eventObj, setEventObj] = useState(null);
  const eventSettings = { dataSource: scheduleData };

  let selectedTarget;
  const menuItems = useMemo(() => [{
    text: 'New Event',
    iconCss: 'e-icons new',
    id: 'Add'
  }, {
    text: 'New Recurring Event',
    iconCss: 'e-icons recurrence',
    id: 'AddRecurrence'
  }, {
    text: 'Today',
    iconCss: 'e-icons today',
    id: 'Today'
  }, {
    text: 'Edit Event',
    iconCss: 'e-icons edit',
    id: 'Save'
  }, {
    text: 'Edit Event',
    id: 'EditRecurrenceEvent',
    iconCss: 'e-icons edit',
    items: [{
      text: 'Edit Occurrence',
      id: 'EditOccurrence'
    }, {
      text: 'Edit Series',
      id: 'EditSeries'
    }]
  }, {
    text: 'Delete Event',
    iconCss: 'e-icons delete',
    id: 'Delete'
  }, {
    text: 'Delete Event',
    id: 'DeleteRecurrenceEvent',
    iconCss: 'e-icons delete',
    items: [{
      text: 'Delete Occurrence',
      id: 'DeleteOccurrence'
    }, {
      text: 'Delete Series',
      id: 'DeleteSeries'
    }]
  }
  ], [])


  const onMenuItemSelect = (args) => {
    let selectedMenuItem = args.item.id;
    if (selectedTarget && selectedTarget.classList.contains('e-appointment')) {
      setEventObj(scheduleObj.current.getEventDetails(selectedTarget));
    }
    switch (selectedMenuItem) {
      case 'Today':
        scheduleObj.current.selectedDate = new Date();
        break;
      case 'Add':
      case 'AddRecurrence':
        let selectedCells = scheduleObj.current.getSelectedElements();
        let activeCellsData = scheduleObj.current.getCellDetails(selectedCells.length > 0 ? selectedCells : selectedTarget);
        if (selectedMenuItem === 'Add') {
          scheduleObj.current.openEditor(activeCellsData, 'Add');
        } else {
          scheduleObj.current.openEditor(activeCellsData, 'Add', null, 1);
        }
        break;
      case 'Save':
      case 'EditOccurrence':
      case 'EditSeries':
        if (selectedMenuItem === 'EditSeries') {
          setEventObj(new DataManager(scheduleObj.current.eventsData).executeLocal(
            new Query().where(scheduleObj.current.eventFields.id,
              'equal', eventObj[scheduleObj.current.eventFields.recurrenceID][0])));
        }
        scheduleObj.current.openEditor(eventObj, selectedMenuItem);
        break;
      case 'Delete':
        scheduleObj.current.deleteEvent(eventObj);
        break;
      case 'DeleteOccurrence':
      case 'DeleteSeries':
        scheduleObj.current.deleteEvent(eventObj, selectedMenuItem);
        break;
    }
  }

  const onContextMenuBeforeOpen = (args) => {
    let newEventElement = document.querySelector('.e-new-event');
    if (newEventElement) {
      remove(newEventElement);
      removeClass([document.querySelector('.e-selected-cell')], 'e-selected-cell');
    }
    scheduleObj.current.closeQuickInfoPopup();
    let targetElement = args.event.target;
    if (closest(targetElement, '.e-contextmenu')) {
      return;
    }
    selectedTarget = closest(targetElement, '.e-appointment,.e-work-cells,' +
      '.e-vertical-view .e-date-header-wrap .e-all-day-cells,.e-vertical-view .e-date-header-wrap .e-header-cells');
    if (isNullOrUndefined(selectedTarget)) {
      args.cancel = true;
      return;
    }
    if (selectedTarget.classList.contains('e-appointment')) {
      setEventObj(scheduleObj.current.getEventDetails(selectedTarget));
      return;
    }
    menuObj.current.hideItems(['Save', 'Delete', 'EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
    menuObj.current.showItems(['Add', 'AddRecurrence', 'Today'], true);
  }
  useEffect(() => {
    if (eventObj && eventObj.RecurrenceRule) {
      menuObj.current.showItems(['EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
      menuObj.current.hideItems(['Add', 'AddRecurrence', 'Today', 'Save', 'Delete'], true);
    } else {
      menuObj.current.showItems(['Save', 'Delete'], true);
      menuObj.current.hideItems(['Add', 'AddRecurrence', 'Today', 'EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
    }
  }, [eventObj]);

  return (
    <div className='schedule-control-section'>
      <div className='control-section'>
        <div className='control-wrapper'>
          <ScheduleComponent height='550px' ref={scheduleObj} selectedDate={new Date(2018, 1, 15)} eventSettings={eventSettings}>
            <ViewsDirective>
              <ViewDirective option='Day' />
              <ViewDirective option='Week' />
              <ViewDirective option='WorkWeek' />
              <ViewDirective option='Month' />
              <ViewDirective option='Agenda' />
            </ViewsDirective>
            <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />
          </ScheduleComponent>
        </div>
      </div>
      <ContextMenuComponent cssClass='schedule-context-menu' ref={menuObj} target='.e-schedule' items={menuItems} beforeOpen={onContextMenuBeforeOpen} select={onMenuItemSelect} />
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('schedule'));
root.render(<App />);
import { useRef, useState, useMemo, useEffect } from 'react';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { closest, isNullOrUndefined, remove, removeClass } from '@syncfusion/ej2-base';
import { Query, DataManager } from '@syncfusion/ej2-data';
import {
  ScheduleComponent, ViewsDirective, ViewDirective, CellClickEventArgs,
  Day, Week, WorkWeek, Month, Agenda, Inject
} from '@syncfusion/ej2-react-schedule';
import { BeforeOpenCloseMenuEventArgs, MenuEventArgs, MenuItemModel, ContextMenuComponent } from '@syncfusion/ej2-react-navigations';
import { scheduleData } from './datasource';

interface EventObject {
  [key: string]: Object;
}

const App = () => {
  const scheduleObj = useRef<ScheduleComponent>(null);
  const menuObj = useRef<ContextMenuComponent>(null);
  const [eventObj, setEventObj] = useState<EventObject | null>(null);
  const eventSettings = { dataSource: scheduleData };

  let selectedTarget: Element;
  const menuItems: MenuItemModel[] = useMemo(() => [{
    text: 'New Event',
    iconCss: 'e-icons new',
    id: 'Add'
  }, {
    text: 'New Recurring Event',
    iconCss: 'e-icons recurrence',
    id: 'AddRecurrence'
  }, {
    text: 'Today',
    iconCss: 'e-icons today',
    id: 'Today'
  }, {
    text: 'Edit Event',
    iconCss: 'e-icons edit',
    id: 'Save'
  }, {
    text: 'Edit Event',
    id: 'EditRecurrenceEvent',
    iconCss: 'e-icons edit',
    items: [{
      text: 'Edit Occurrence',
      id: 'EditOccurrence'
    }, {
      text: 'Edit Series',
      id: 'EditSeries'
    }]
  }, {
    text: 'Delete Event',
    iconCss: 'e-icons delete',
    id: 'Delete'
  }, {
    text: 'Delete Event',
    id: 'DeleteRecurrenceEvent',
    iconCss: 'e-icons delete',
    items: [{
      text: 'Delete Occurrence',
      id: 'DeleteOccurrence'
    }, {
      text: 'Delete Series',
      id: 'DeleteSeries'
    }]
  }
  ], [])


  const onMenuItemSelect = (args: MenuEventArgs): void => {
    let selectedMenuItem: string = args.item.id;
    if (selectedTarget && selectedTarget.classList.contains('e-appointment')) {
      setEventObj(scheduleObj.current!.getEventDetails(selectedTarget) as EventObject);
    }
    switch (selectedMenuItem) {
      case 'Today':
        scheduleObj.current!.selectedDate = new Date();
        break;
      case 'Add':
      case 'AddRecurrence':
        let selectedCells: Element[] = scheduleObj.current!.getSelectedElements();
        let activeCellsData: CellClickEventArgs =
          scheduleObj.current!.getCellDetails(selectedCells.length > 0 ? selectedCells : selectedTarget);
        if (selectedMenuItem === 'Add') {
          scheduleObj.current!.openEditor(activeCellsData, 'Add');
        } else {
          scheduleObj.current!.openEditor(activeCellsData, 'Add', null, 1);
        }
        break;
      case 'Save':
      case 'EditOccurrence':
      case 'EditSeries':
        if (selectedMenuItem === 'EditSeries') {
          setEventObj(new DataManager(scheduleObj.current!.eventsData).executeLocal(
            new Query().where(scheduleObj.current!.eventFields.id,
              'equal', eventObj[scheduleObj.current!.eventFields.recurrenceID] as string | number))[0] as EventObject);
        }
        scheduleObj.current!.openEditor(eventObj!, selectedMenuItem);
        break;
      case 'Delete':
        scheduleObj.current!.deleteEvent(eventObj!);
        break;
      case 'DeleteOccurrence':
      case 'DeleteSeries':
        scheduleObj.current!.deleteEvent(eventObj!, selectedMenuItem);
        break;
    }
  }

  const onContextMenuBeforeOpen = (args: BeforeOpenCloseMenuEventArgs): void => {
    let newEventElement: HTMLElement = document.querySelector('.e-new-event') as HTMLElement;
    if (newEventElement) {
      remove(newEventElement);
      removeClass([document.querySelector('.e-selected-cell')], 'e-selected-cell');
    }
    scheduleObj.current!.closeQuickInfoPopup();
    let targetElement: HTMLElement = args.event.target as HTMLElement;
    if (closest(targetElement, '.e-contextmenu')) {
      return;
    }
    selectedTarget = closest(targetElement, '.e-appointment,.e-work-cells,' +
      '.e-vertical-view .e-date-header-wrap .e-all-day-cells,.e-vertical-view .e-date-header-wrap .e-header-cells');
    if (isNullOrUndefined(selectedTarget)) {
      args.cancel = true;
      return;
    }
    if (selectedTarget.classList.contains('e-appointment')) {
      setEventObj(scheduleObj.current!.getEventDetails(selectedTarget) as EventObject);
      return;
    }
    menuObj.current!.hideItems(['Save', 'Delete', 'EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
    menuObj.current!.showItems(['Add', 'AddRecurrence', 'Today'], true);
  }
  useEffect(() => {
    if (eventObj && eventObj.RecurrenceRule) {
      menuObj.current!.showItems(['EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
      menuObj.current!.hideItems(['Add', 'AddRecurrence', 'Today', 'Save', 'Delete'], true);
    } else {
      menuObj.current!.showItems(['Save', 'Delete'], true);
      menuObj.current!.hideItems(['Add', 'AddRecurrence', 'Today', 'EditRecurrenceEvent', 'DeleteRecurrenceEvent'], true);
    }
  }, [eventObj]);

  return (
    <div className='schedule-control-section'>
      <div className='control-section'>
        <div className='control-wrapper'>
          <ScheduleComponent height='550px' ref={scheduleObj} selectedDate={new Date(2018, 1, 15)} eventSettings={eventSettings}>
            <ViewsDirective>
              <ViewDirective option='Day' />
              <ViewDirective option='Week' />
              <ViewDirective option='WorkWeek' />
              <ViewDirective option='Month' />
              <ViewDirective option='Agenda' />
            </ViewsDirective>
            <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />
          </ScheduleComponent>
        </div>
      </div>
      <ContextMenuComponent cssClass='schedule-context-menu' ref={menuObj} target='.e-schedule' items={menuItems} beforeOpen={onContextMenuBeforeOpen} select={onMenuItemSelect} />
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('schedule'));
root.render(<App />);
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React Schedule</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-base/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-buttons/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-calendars/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-dropdowns/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-inputs/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-navigations/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-popups/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/32.1.19/ej2-react-schedule/styles/tailwind3.css" rel="stylesheet" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="index.css" rel="stylesheet" />    
    <script src="systemjs.config.js"></script>
     <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
        <div id='schedule'>
            <div id='loader'>Loading....</div>
        </div>
</body>

</html>
.schedule-context-menu .e-menu-item .new::before {
  content: '\e7f9';
}

.schedule-context-menu .e-menu-item .edit::before {
  content: '\ea9a';
}

.schedule-context-menu .e-menu-item .recurrence::before {
  content: '\e308';
  font-weight: bold;
}

.schedule-context-menu .e-menu-item .today::before {
  content: '\e322';
}

.schedule-context-menu .e-menu-item .delete::before {
  content: '\e94a';
}

.e-bigger .schedule-context-menu ul .e-menu-item .e-menu-icon {
  font-size: 14px;
}

.schedule-context-menu ul .e-menu-item .e-menu-icon {
  font-size: 12px;
}

You can refer to our React Scheduler feature tour page for its groundbreaking feature representations. You can also explore our React Scheduler example to knows how to present and manipulate data.