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 web part
Display calendar events
Calendar events for the logged-in user are displayed below.
![My event]()
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 web part.
yo @microsoft/sharepoint
Enter all the required details to create a new solution, as shown below.
![Create a new project]()
A Yeoman generator will perform the scaffolding process. Once it is completed, lock down the version of project dependencies by executing the following command:
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
![Folder structure]()
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.
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "spfx-graph-api-samples-client-side-solution",
"id": "a452f2ac-837b-41db-9370-b3c872cbe376",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "Calendars.Read"
}
]
},
"paths": {
"zippedPackage": "solution/spfx-graph-api-samples.sppkg"
}
}
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.
export interface IEvent {
subject: string;
organizer?: string;
start?: string;
end?: string;
}
export interface IEventColl {
value: IEvent[];
}
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.
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.
import { IEvent, IEventColl } from '../models/IEvent';
export interface IGraphListCalendarEventsState {
events?: IEvent[];
}
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.
import { MSGraphClient } from "@microsoft/sp-http";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { IEvent, IEventColl } from "../models";
export class CalendarService {
public context: WebPartContext;
public setup(context: WebPartContext): void {
this.context = context;
}
public getEvents(): Promise<IEvent[]> {
return new Promise<IEvent[]>((resolve, reject) => {
try {
// Prepare the output array
var events: Array<IEvent> = new Array<IEvent>();
this.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient) => {
client
.api("/me/events")
.select('subject,organizer,start,end')
.get((error: any, eventColl: IEventColl, rawResponse: any) => {
// Map the response to the output array
eventColl.value.map((item: any) => {
events.push({
subject: item.subject,
organizer: item.organizer.emailAddress.name,
start: item.start.dateTime,
end: item.end.dateTime
});
});
resolve(events);
});
});
} catch (error) {
console.error(error);
}
});
}
}
const calendarService = new CalendarService();
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.
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
import calendarService, { CalendarService } from './services/CalendarService';
Update the OnInit method
protected onInit(): Promise<void> {
return super.onInit().then(() => {
calendarService.setup(this.context);
});
}
Open “src\webparts\graphListcalendarevents\components\GraphListcalendarevents.tsx” file and import the modules.
import { IGraphListCalendarEventsState } from './IGraphListcalendareventsState';
import { IEvent, IEventColl } from '../models/IEvent';
import CalendarService from '../services/CalendarService';
import { List } from 'office-ui-fabric-react/lib/List';
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
Update the render method, as shown below.
public render(): React.ReactElement<IGraphListcalendareventsProps> {
const { events = [] } = this.state;
return (
<div className={styles.graphListcalendarevents}>
<h1>My Events:</h1>
<ListView
items={this.state.events}
compact={true}
selectionMode={SelectionMode.none}
/>
</div>
);
}
Call the Calendar Service to retrieve the events.
public _getEvents = (): void => {
CalendarService.getEvents().then(result => {
this.setState({
events: result
});
});
}
Updated React component (src\webparts\graphListcalendarevents\components\GraphListcalendarevents.tsx).
import * as React from 'react';
import styles from './GraphListcalendarevents.module.scss';
import { IGraphListcalendareventsProps } from './IGraphListcalendareventsProps';
import { IGraphListCalendarEventsState } from './IGraphListcalendareventsState';
import { escape } from '@microsoft/sp-lodash-subset';
import { IEvent, IEventColl } from '../models/IEvent';
import CalendarService from '../services/CalendarService';
import { List } from 'office-ui-fabric-react/lib/List';
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
export default class GraphListcalendarevents extends React.Component<IGraphListcalendareventsProps, IGraphListCalendarEventsState> {
constructor(props: IGraphListcalendareventsProps) {
super(props);
this.state = {
events: []
};
}
public componentDidMount(): void {
this._getEvents();
}
public render(): React.ReactElement<IGraphListcalendareventsProps> {
const { events = [] } = this.state;
return (
<div className={styles.graphListcalendarevents}>
<h1>My Events:</h1>
<ListView
items={this.state.events}
compact={true}
selectionMode={SelectionMode.none}
/>
</div>
);
}
public _getEvents = (): void => {
CalendarService.getEvents().then(result => {
this.setState({
events: result
});
});
}
}
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.