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
npm install @microsoft/microsoft-graph-types --save-dev
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”
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
Open “IMyUserInformationProps” properties interface import the web part context from sp-webpart-base
import { WebPartContext } from "@microsoft/sp-webpart-base";
Add the “WebPartContext” properties inside the interface the final code look like below
import {WebPartContext } from "@microsoft/sp-webpart-base";
export interface IMyUserInformationProps {
description: string;
context: WebPartContext
}
Open “MyUserInformationWebPart.ts” include the context inside render()
public render(): void {
const element: React.ReactElement<IMyUserInformationProps> = React.createElement(
MyUserInformation,
{
context: this.context,
description: this.properties.description,
}
);
ReactDom.render(element, this.domElement);
}
Create a state interface to hold the data of user profile object
export interface IUserInformationState {
data: {}
}
Initialize the constructor to declare the props and state
export default class MyEvents extends React.Component<IMyEventsProps, IUserInformationState> {
constructor(props: IMyEventsProps) {
super(props);
this.state = {
data: {}
}
}
Create a function named “GetMyProfile()” to fetch the current user information
const GetMyProfile = () => {
this.props.context.msGraphClientFactory.getClient('3').then((client): void => {
client.api('me').get((error, user: MicrosoftGraph.User, rawResponse?: any) => {
this.setState({
data: user
})
}
In “ComponetDidMount()” pass the created function it will retrieve the user information when page renders
componentDidMount(): void {
this.GetMyProfile()
}
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






Join the conversation! Your thoughts help the community grow.