Display Calendar Events Using Graph API in SharePoint Framework

Introduction 

 
In this article, you will see how to display calendar events using Graph API in SharePoint Framework by performing the following tasks:
  • Create an SPFx solution
  • Implement the SPFx solution
  • Deploy the solution
  • Approve Graph API Permissions
  • Test the webpart

Display Calendar Events

 
Calendar events for the logged-in user are displayed below.
 
Display Calendar Events Using Graph API In SharePoint Framework 
 
Prerequisites

Create a SPFx solution

 
Open the Node.js command prompt.
 
Create a new folder.
 
>md spfx-graphAPI-samples
 
Navigate to the folder.
 
>cd spfx-graphAPI-samples
 
Execute the following command to create the SPFx webpart.
 
>yo @microsoft/sharepoint
 
Enter all the required details to create a new solution, as shown below:
 
Display Calendar Events Using Graph API In SharePoint Framework 
 
Yeoman generator will perform the scaffolding process. Once it is completed, lock down the version of project dependencies by executing the following command:
 
>npm shrinkwrap
 
Execute the following command to open the solution in the code editor:
 
>code .
 

Implement the SPFx Solution

 
Execute the following command to install the PnP React Controls NPM package:
 
>npm install @pnp/spfx-controls-react –save
 
Execute the following command to install Microsoft Graph Typings:
 
> npm install @microsoft/microsoft-graph-types
 
Folder Structure
 
Display Calendar Events Using Graph API In SharePoint Framework 
 
Open package-solution.json “config\package-solution.json” file and update the code, as shown below:
 
Note
In order to get all the events using Graph API, Calendars.Read permission is required.
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",  
  3.   "solution": {  
  4.     "name""spfx-graph-api-samples-client-side-solution",  
  5.     "id""a452f2ac-837b-41db-9370-b3c872cbe376",  
  6.     "version""1.0.0.0",  
  7.     "includeClientSideAssets"true,  
  8.     "isDomainIsolated"false,  
  9.     "webApiPermissionRequests": [  
  10.       {  
  11.         "resource""Microsoft Graph",  
  12.         "scope""Calendars.Read"  
  13.       }  
  14.     ]  
  15.   },  
  16.   "paths": {  
  17.     "zippedPackage""solution/spfx-graph-api-samples.sppkg"  
  18.   }  
  19. }  
Create a new folder named “models” inside src\webparts\graphListcalendarevents folder. Create a new file named IEvent.ts. Open the“src\webparts\graphListcalendarevents\models\IEvent.ts” file and update the code, as shown below:
  1. export interface IEvent {  
  2.     subject: string;  
  3.     organizer?: string;  
  4.     start?: string;  
  5.     end?: string;  
  6. }  
  7.   
  8. export interface IEventColl{  
  9.     value: IEvent[];  
  10. }  
Create a new file named index.ts under the models folder. Open “src\webparts\graphListcalendarevents\models\index.ts” file and update the code as shown below:
  1. export * from './IEvent';  
Create a new file named as IGraphListcalendareventsState.ts under components folder. Open the “src\webparts\graphListcalendarevents\components\IGraphListcalendareventsState.ts” file and update the code, as shown below:
  1. import {IEvent, IEventColl} from '../models/IEvent';  
  2. export interface IGraphListCalendarEventsState{  
  3.     events?: IEvent[];  
  4. }  
Create a new folder named as “services” inside src\webparts\graphListcalendarevents folder. Create a new file named CalendarService.ts. Open “src\webparts\graphListcalendarevents\services\CalendarService.ts” file and update the code, as shown below. Import all the required modules and create an getEvents method which will retrieve events from the Calendar using Graph API.
  1. import { MSGraphClient } from "@microsoft/sp-http";  
  2. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  3. import { IEvent, IEventColl } from "../models";  
  4.   
  5. export class CalendarService {  
  6.     public context: WebPartContext;  
  7.   
  8.     public setup(context: WebPartContext): void {  
  9.         this.context = context;  
  10.     }  
  11.   
  12.     public getEvents(): Promise<IEvent[]> {  
  13.         return new Promise<IEvent[]>((resolve, reject) => {  
  14.             try {  
  15.                 // Prepare the output array    
  16.                 var events: Array<IEvent> = new Array<IEvent>();  
  17.   
  18.                 this.context.msGraphClientFactory  
  19.                     .getClient()  
  20.                     .then((client: MSGraphClient) => {  
  21.                         client  
  22.                             .api("/me/events")  
  23.                             .select('subject,organizer,start,end')  
  24.                             .get((error: any, eventColl: IEventColl, rawResponse: any) => {  
  25.                                 // Map the response to the output array    
  26.                                 eventColl.value.map((item: any) => {  
  27.                                     events.push({                                          
  28.                                         subject: item.subject,  
  29.                                         organizer: item.organizer.emailAddress.name,  
  30.                                         start: item.start.dateTime,  
  31.                                         end: item.end.dateTime  
  32.                                     });  
  33.                                 });  
  34.                                 resolve(events);  
  35.                             });  
  36.                     });  
  37.             } catch (error) {  
  38.                 console.error(error);  
  39.             }  
  40.         });  
  41.     }  
  42. }  
  43.   
  44. const calendarService = new CalendarService();  
  45. export default calendarService;  
Create a new file named index.ts under the services folder. Open “src\webparts\graphListcalendarevents\services\index.ts” file and update the code, as shown below.
  1. import calendarService, { CalendarService } from './services/CalendarService';  
Open “src\webparts\graphListcalendarevents\GraphListcalendareventsWebPart.ts” file and update the following.
  • Import modules
  • Update the OnInit method
Import modules:
  1. import calendarService, { CalendarService } from './services/CalendarService';  
Update the OnInit method:
  1. protected onInit(): Promise<void> {  
  2.     return super.onInit().then(() => {  
  3.       calendarService.setup(this.context);  
  4.     });  
  5.   }  
Open “src\webparts\graphListcalendarevents\components\GraphListcalendarevents.tsx” file and import the modules.
  1. import { IGraphListCalendarEventsState } from './IGraphListcalendareventsState';  
  2. import { IEvent, IEventColl } from '../models/IEvent';  
  3. import CalendarService from '../services/CalendarService';  
  4. import { List } from 'office-ui-fabric-react/lib/List';  
  5. import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";  
Update the render method, as shown below:
  1. public render(): React.ReactElement<IGraphListcalendareventsProps> {  
  2.   const { events = [] } = this.state;  
  3.   return (  
  4.     
  5.     <div className={styles.graphListcalendarevents}>  
  6.       <h1>My Events:</h1>  
  7.       <ListView  
  8.         items={this.state.events}  
  9.         compact={true}  
  10.         selectionMode={SelectionMode.none}  
  11.       />  
  12.     </div>  
  13.   );  
  14. }   
Call the Calendar Service to retrieve the events.
  1. public _getEvents = (): void => {  
  2.    CalendarService.getEvents().then(result => {  
  3.      this.setState({  
  4.        events: result  
  5.      });  
  6.    });  
  7.  }   
Updated React component (src\webparts\graphListcalendarevents\components\GraphListcalendarevents.tsx),
  1. import * as React from 'react';  
  2. import styles from './GraphListcalendarevents.module.scss';  
  3. import { IGraphListcalendareventsProps } from './IGraphListcalendareventsProps';  
  4. import { IGraphListCalendarEventsState } from './IGraphListcalendareventsState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6. import { IEvent, IEventColl } from '../models/IEvent';  
  7. import CalendarService from '../services/CalendarService';  
  8. import { List } from 'office-ui-fabric-react/lib/List';  
  9. import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";  
  10.   
  11. export default class GraphListcalendarevents extends React.Component<IGraphListcalendareventsProps, IGraphListCalendarEventsState> {  
  12.   constructor(props: IGraphListcalendareventsProps) {  
  13.     super(props);  
  14.     this.state = {  
  15.       events: []  
  16.     };  
  17.   }  
  18.   
  19.   public componentDidMount(): void {  
  20.     this._getEvents();  
  21.   }  
  22.   
  23.   public render(): React.ReactElement<IGraphListcalendareventsProps> {  
  24.     const { events = [] } = this.state;  
  25.     return (  
  26.       
  27.       <div className={styles.graphListcalendarevents}>  
  28.         <h1>My Events:</h1>  
  29.         <ListView  
  30.           items={this.state.events}  
  31.           compact={true}  
  32.           selectionMode={SelectionMode.none}  
  33.         />  
  34.       </div>  
  35.     );  
  36.   }  
  37.   
  38.   public _getEvents = (): void => {  
  39.     CalendarService.getEvents().then(result => {  
  40.       this.setState({  
  41.         events: result  
  42.       });  
  43.     });  
  44.   }  
  45. }  

Deploy the solution

 
Execute the following commands to bundle and package the solution.
 
>gulp bundle --ship
>gulp package-solution --ship
 
Navigate to tenant app catalog – Example - https://c986.sharepoint.com/sites/appcatalog/SitePages/Home.aspx
 
Upload the package file (sharepoint\solution\spfx-graph-api-samples.sppkg). Click Deploy.
 

Approve Graph API permissions

 
Navigate to SharePoint Admin center and click API access in the left navigation. Select the permission requested for this web app and click Approve.
 
Display Calendar Events Using Graph API In SharePoint Framework
 
Display Calendar Events Using Graph API In SharePoint Framework 
 

Test the webpart 

 
Navigate to the SharePoint site and add the app.
 
Display Calendar Events Using Graph API In SharePoint Framework 
 
Navigate to the page and add the webpart.
 
Display Calendar Events Using Graph API In SharePoint Framework 
 

Summary

 
In this article, you saw how to display calendar events using Graph API in SharePoint Framework.