Exploring SharePoint Framework (SPFx): Building Custom Web Parts with React and Microsoft Graph API — Part I
Introduction
I often found myself pondering whether to write this article, considering that SharePoint developers represent a relatively small percentage of web developers. I questioned who would take the time to read it. However, I realized that someone in my shoes would have greatly appreciated such guidance, so here I am, sharing my journey of exploring SharePoint Framework (SPFx).
My journey began when I was tasked with building a SharePoint site for a client. Initially, we expected it to be a low-to-no-code project. But as it turned out, the client had ambitious requirements that couldn’t be fulfilled with SharePoint’s out-of-the-box web parts alone. This challenge led me to dive into the world of SPFx.
Throughout this series, I aim to fill the gap in resources I encountered during my exploration. I’ll provide insights into SharePoint Framework,the fundamental knowledge I acquired along the way and useful resources that helped me. My hope is that this series will be a valuable resource for anyone embarking on a similar journey.
So, to all those who may find this information useful: Welcome! Your feedback and questions are always appreciated.
Building your first web part
Let’s begin by setting up the custom web part. To start, select a directory where you’d like to create the web part. We’ll create a parent folder called “spfx_series” and within it, we’ll make sub folders for each web part we develop throughout this series. You can easily accomplish this by using the “mkdir” command in your command prompt or shell on your computer.
Next, navigate to the directory you just created by using the ‘cd’ command. Once inside the directory, run the following command:
npm install gulp-cli yo @microsoft/generator-sharepoint --global
This command serves to install ‘gulp,’ a JavaScript-based task runner that SharePoint uses for project builds, as well as the Yeoman SharePoint web part generator. Yeoman helps you swiftly create SharePoint client-side solution projects with the correct tool chain and project structure.
Note: It’s recommended to use the following node versions: ‘>=12.13.0 <13.0.0 || >=14.15.0 <15.0.0 || >=16.13.0 <17.0.0’ for compatibility with the SharePoint Framework.”
After successfully installing Gulp and Yeoman with the previous commands, run the ‘yo @microsoft/sharepoint’ command on your command prompt.
yo @microsoft/sharepoint
The Yeoman SharePoint Generator will initiate and present you with a set of questions. For most of these questions, it’s advisable to stick with the default options. However, take note of the following questions where you should make these selections:
- Solution name: MyMeetings
- Type of client-side component to create: WebPart
- Web part name: MyMeetings
- Template of choice: React
Once the Yeoman generator completes and the SharePoint Framework project is created, proceed by executing the following command. Be sure to run this command from within the root folder of the project:
gulp trust-dev-cert
Note: It’s essential to run this command only during the first/initial build of your project. It creates a local certificate that allows you to run your web part on Sharepoint Online for testing and debugging. It’s not necessary to repeat it for every SPFX project.
Great! now open the ‘spfx_series’ folder in your code editor. Inside this folder, navigate to ‘spfx_series\meetings_webpart\config\serve.json. Modify the code below by replacing the curly brackets with your site url.
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "{siteUrl}/_layouts/workbench.aspx" // replace with your site url
}
Then run ‘gulp serve’ on your terminal.
gulp serve
If you see the screen below, Congratulations! you have just set up your first custom web part.
Building ‘MyMeetings’ web part
We are going to create a web part with a specific purpose: to read through a user’s Outlook calendar and display the events that have been added to that user’s calendar. If you work in a company, you’re likely familiar with the fact that many of these events are, in fact, meetings. Hence, we’ve aptly named our web part “MyMeetings.”
Now that we’ve set up our first custom web part, it’s time to understand the changes we’ll be making to the source code. While I won’t be able to list or explain every single change in this article, I’ll focus on one crucial function: the one responsible for reading user events.
The majority of these changes will be made to the MyMeetings.tsx
file, where we handle the core functionality of fetching and displaying calendar events.I have included the link to the GitHub repository which shows the complete code used for this web part.
Before we get into it, you might be wondering how we are going to accomplish this. We have essentially created a web part, and we already know how we want the front-end (view GitHub to see code) to look. Now, let’s discuss how we are going to retrieve the user’s meetings/events from Outlook. We will do this by using the Microsoft Graph API.
Microsoft Graph, in a nutshell, provides access to data stored across Microsoft 365 services, which include Microsoft Teams, Outlook, OneDrive, etc. In simpler terms, it consists of a library of APIs/endpoints that you, as a developer, can leverage to retrieve information/data from any of the above-listed platforms. You can read more about it here.
The end point we would be leveraging is:
GET /me/calendar/calendarView?startDateTime={start_datetime}&endDateTime={end_datetime}
// where these parameters define the range for querying or viewing events, specifying the start date and time of the events you want to access.
I have used this endpoint in the function below:
// This function utilizes MSGraphClientV3 to connect with Microsoft Graph.
// We access the msGraphClientFactory through the web part's context.
// This function gets the logged in users meeting from outlook calender.
const getUserMeetings = async (): Promise<void> => {
try{
await props.spcontext.msGraphClientFactory
.getClient('3')
.then((client: MSGraphClientV3):void => {
client
.api(`/me/calendar/calendarView?startDateTime=${moment().utc().format()}&endDateTime=${moment().endOf('day').utc().format()}`)
.select('id, subject, start, end')
.orderby('start/dateTime')
.get((err: unknown, res: IMeetingRes) => {
//handle response
if (err) {
console.log("MSGraphAPI Error")
console.error(err);
return;
}
setMeeting(res.value);
});
})
}catch(err){
console.log("MSGraphAPI Error")
console.error(err);
}finally{
setIsLoadingMeeting(false);
}
}
The function above uses MSGraphClientV3 to establish a connection to Microsoft Graph. This can be accessed through the MSGraphClientFactory which is available in the web parts’ context. Using JavaScript client library syntax, we initiate communication with Microsoft Graph.
We construct an API request, targeting ‘/me/calendar/calendarView’. The parameters ‘startDateTime’ and ‘endDateTime’ are dynamically generated using the moment.js library. This will ensure we fetch events only for the current day, with accurate start and end times. We select the ‘event id,’ ‘subject,’ ‘start time,’ and ‘end time’ as these are the necessary fields needed for the UI display. The response is then ordered chronologically by ‘the start time’.
In case of API request errors, we log them. Conversely, upon a successful request, we update the ‘meeting’ state with the response data. Finally, we set ‘isLoadingMeeting’ to ‘false’ to indicate the completion of the process.
NOTE: MSGraphClientV3 is compatible with projects developed using SharePoint Framework v1.15.0 or later. For earlier versions, the ‘MSGraphClient’ was employed.
Now that we’ve successfully fetched the data needed for the Meetings web part, there’s one essential step to ensure it runs smoothly in your company’s/organisation’s SharePoint environment. You may need to approve the API access in your company’s SharePoint Admin Center before the web part can function correctly. Therefore, it’s crucial to have sufficient privileges (Global or Tenant) within your company’s SharePoint or Microsoft 365 environment. Without these privileges, some functionalities may not work as expected.
You can go ahead and run ‘gulp serve’ again if you haven’t already. If you see the screen below:
You’ve successfully utilized the Microsoft Graph API to build a web part that displays a user’s meetings. Keep in mind that if you don’t have any scheduled meetings, the web part will appear empty.
To deploy this web part, run the following commands
gulp bundle --ship
gulp package-solution --ship
This will generate a file with the .sppkg extension, which serves as your web part’s package. You can then add this package to your SharePoint site as an app through the SharePoint Admin Center. Access the admin center using this URL:
{siteUrl}/sites/appcatalog/_layouts/15/tenantAppCatalog.aspx/manageApps
Congratulations for coming this far !
Please feel free to explore the complete source code on my GitHub repository https://github.com/Simplyvoda/spfx_series as I have done proper documentation on changes made to the web part’s source code. If you have any questions or suggestions regarding best practices or need assistance with any aspect of this project, please don’t hesitate to contact me. Your feedback and inquiries are always welcome and appreciated.
Thank You.