How to integrate outlook calendar in React Scheduler?
This knowledge base article explains how to integrate outlook calendar events with Syncfusion React scheduler.
Key points:
Create a React app that a user can log in to using their Microsoft 365 Developer Program account.
Use Microsoft Graph to get the user’s Microsoft Outlook Calendar events.
Display the Microsoft Outlook Calendar events in our Syncfusion react scheduler.
Prerequisites:
Node.js version 18+
Need to have a personal Microsoft account or a Microsoft work or school account.
Step 1: Register a web application with the Azure Active Directory admin center.
As a first step we need to register an application in Azure active directory using the below steps.
Using that Microsoft account, enroll in the Microsoft 365 Developer Program. You will be asked what areas of Microsoft 365 development you are interested in when you join the Microsoft 365 Developer Program; choose Microsoft Graph. After creating your admin username and password and selecting the nearest data center area, click "Continue." Click "Next" after choosing "Instant Sandbox."
Open a browser and navigate to the Azure Active Directory admin center. Login using a personal account (aka: Microsoft Account) or Work or School Account.
Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.
Select New registration. On the Register an application page, set the values as follows.
Set Name as MyScheduler
Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
Under Redirect URI, set the first drop-down to Single-page application (SPA) and set the value to http://localhost:3000.
Choose Register. On the MyScheduler, copy the value of the Application (client) ID and save it, you will need it in the next step.
Step 2: Create a React app that a user can log in to using their Microsoft 365 Developer Program account:
Create a React scheduler sample using the getting started(https://ej2.syncfusion.com/react/documentation/schedule/getting-started)
Import Scheduler packages and styles.
Configure the sample:
Create a folder inside src folder namely Config.ts and add the below codes. In that file replace the value of appId with your Application Id got from the App Registration Portal.
const config = { appId: ‘Your application Id’, redirectUri: 'http://localhost:3000', scopes: [ 'user.read', 'mailboxsettings.read', 'calendars.readwrite' ] }; export default config; |
On the Index page(index.ts) we need setup the MSAL (Microsoft Authentication Library) configurations to handle logging in with Microsoft accounts.
const msalInstance = new PublicClientApplication({ auth: { clientId: config.appId, redirectUri: config.redirectUri }, cache: { cacheLocation: 'sessionStorage', storeAuthStateInCookie: true } }); |
-----
In your command-line interface (CLI), navigate to the graph-tutorial directory and run the following command to install requirements.
yarn install
-----
Welcome Page:
Create a new file (Welcome.tsx) for the welcome page which include greetings and a sign in button.
import { Button, Container } from 'react-bootstrap'; import {AuthenticatedTemplate, UnauthenticatedTemplate} from '@azure/msal-react'; import {useAppContext} from './AppContext'; export default function Welcome() { const app = useAppContext();
return ( <div className="p-5 mb-4 bg-light rounded-3"> <Container fluid> <h1>Scheduler Outlook Integration</h1> <p className="lead"> This sample app shows how to use the Microsoft Graph API to access a user's data from React </p> <AuthenticatedTemplate> <div> <h4>Welcome {app.user?.displayName || ''}!</h4> <p>Use the navigation bar at the top of the page to get started.</p> </div> </AuthenticatedTemplate> <UnauthenticatedTemplate> <Button color="primary" onClick={app.signIn!}>Click here to sign in</Button> </UnauthenticatedTemplate> </Container> </div> ); }
|
Add a new file under the source folder namely App.context.ts which helps us to manage user information and errors in a React app, it also handles signing in and signing out using Microsoft services.
Create a new file (GraphService.ts) file under source folder and add the following codes in it, which makes the client to get ready to connect with the Microsoft API using AUTH Provider, which helps make sure the person using the program is allowed to access the information.
let graphClient: Client | undefined = undefined; function ensureClient(authProvider: AuthCodeMSALBrowserAuthenticationProvider) { if (!graphClient) { graphClient = Client.initWithMiddleware({ authProvider: authProvider }); } return graphClient; } |
Next you can fetch the user information from the Microsoft Graph API using the getUser method as follows:
export async function getUser(authProvider: AuthCodeMSALBrowserAuthenticationProvider): Promise<User> { ensureClient(authProvider); const user: User = await graphClient!.api('/me') .select('displayName,mail,mailboxSettings,userPrincipalName') .get(); return user; }
|
You can get your calendar and its events for the week using below codes:
export async function getUserWeekCalendar(authProvider: AuthCodeMSALBrowserAuthenticationProvider, timeZone: string, startDate: Date, endDate:Date): Promise<Event[]> { ensureClient(authProvider); // Generate startDateTime and endDateTime query params // to display a 7-day window const startDateTime = zonedTimeToUtc(startDate, timeZone).toISOString(); const endDateTime = zonedTimeToUtc(endDate, timeZone).toISOString(); // GET /me/calendarview?startDateTime=''&endDateTime='' // &$select=subject,organizer,start,end // &$orderby=start/dateTime // &$top=50 var response: PageCollection = await graphClient! .api('/me/calendarview') .header('Prefer', `outlook.timezone="${timeZone}"`) .query({ startDateTime: startDateTime, endDateTime: endDateTime }) .select('subject,organizer,start,end,recurrence') .orderby('start/dateTime') .top(25) .get();
if (response["@odata.nextLink"]) { // Presence of the nextLink property indicates more results are available // Use a page iterator to get all results var events: Event[] = [];
// Must include the time zone header in page // requests too var options: GraphRequestOptions = { headers: { 'Prefer': `outlook.timezone="${timeZone}"` } }; var pageIterator = new PageIterator(graphClient!, response, (event) => { events.push(event); return true; }, options); await pageIterator.iterate(); const schedulerEvents: any = events.map((event) => ({ ...event, subject: event.subject, start: event.start?.dateTime, end: event.end?.dateTime, startTimezone: event.start?.timeZone, endTimezone: event.end?.timeZone, recurrence: event.recurrence })); return schedulerEvents; } else { const schedulerEvents = response.value.map((event) => ({ ...event, subject: event.subject, start: event.start.dateTime, end: event.end.dateTime, startTimezone: event.start.timeZone, endTimezone: event.end.timeZone, recurrence: event.recurrence })); return schedulerEvents; } } |
Let’s create a new folder namely Scheduler.tsx under the source folder and include Schedule component related codes in it.
Field mapping:
Since the fields received from the outlook have different mapping names compared to the scheduler datasource collections field names, it is necessary to map the equivalent field name within the eventSettings property.
Refer to the documentation below for more details.
https://ej2.syncfusion.com/react/documentation/schedule/appointments#binding-different-field-names
In GrapService.ts file add the below highlighted codes to map the fields correctly to our scheduler since the data received from the outlook contains array of datetime and timezone in the start and end properties, hence need to assign them to the respective fields.
schedulerEvents = response.value.map((event) => ({ ...event, subject: event.subject, start: event.start.dateTime, end: event.end.dateTime, startTimezone: event.start.timeZone, endTimezone: event.end.timeZone, recurrence: event.recurrence })); return schedulerEvents; |
Run the sample
Run the following command in your CLI to start the application.
yarn start
Open a browser and browse to http://localhost:3000.
Outlook events integrated into scheduler:
Sample link: https://github.com/SyncfusionExamples/outlook-calendar-integration-react-scheduler
Conclusion:
I hope you enjoyed learning about how to integrate outlook calendar into React Scheduler.
You can refer to our React Scheduler feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Scheduler example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!