In this article, I have explained how to get the current user profile properties in your SPFx webpart using Microsoft Graph API

Create a SPFx project with “Webpart” template & choose the framework “React”

 

Install the necessary “NPM” packages and am going to use “MSGraphClient” to connect my webpart SPFx with Microsoft Graph API

Microsoft graph types help us to catch the error in your Typescript code faster.

Import the necessary packages in “MyUserInformation.tsx” file under “src\webparts\components

Open “IMyUserInformationProps” properties interface import the web part context from sp-webpart-base

Add the “WebPartContext” properties inside the interface the final code look like below

Open “MyUserInformationWebPart.ts” include the context inside render()

Create a state interface to hold the data of user profile object

Initialize the constructor to declare the props and state

Create a function named “GetMyProfile()” to fetch the current user information

In “ComponetDidMount()” pass the created function it will retrieve the user information when page renders

Create a child component “UserDetail.tsx” to display user information details. Here I am using parent and child concept in components and send the retrieved data over props

Include the properties interface in your class component look like below

 

Import the UserDetail.tsx child component in to your parent component “MyUserInformation.tsx”

Inside the render() method pass the component and data over props

Now open the child component “UserDetail.tsx” get the data from the props and render it into your HTML element based on your UI.

 

Full code

MyUserInformation.tsx

UserDetail.tsx

Before running the webpart include the below permission scopes inside your package-solution.json, You can include multiple permission scopes based on your application requirement

After a successful deployment of your webpart, Open SharePoint admin center choose “Advanced -> API Access” from left navigation window.

Approve your permission scope “User.Read.All” is displayed on “Pending requests”

 

Hit “Gulp Serve” and run the webpart.

hostforlifebanner