You have two options to check if the current user is a member of a specific group in SharePoint SPFX as the following:
- Using REST API
- Using Microsoft Graph
1) Check if current user is a member of group using REST API in SharePoint
To get the list of groups in which a user is a member, you can use this endpoint _api/Web/CurrentUser/Groups
function checkMemberGroups() {
var absoluteUri = _spPageContextInfo.webAbsoluteUrl;
var UserInGroup = false;
var UserGroup = "Enter your group name that you would like to check"
$.ajax({
async: false,
headers: {
"accept": "application/json; odata=verbose"
},
method: "GET",
url: absoluteUri + "_api/Web/CurrentUser/Groups",
success: function(data) {
success: function(data) {
for (var i = 0; i < data.d.Groups.results.length; i++) {
if (data.d.Groups.results[i].Title == UserGroup) {
UserInGroup = true;
}
}
},
error: function(response) {
console.log(response.status);
},
});
return UserInGroup;
}
You can use the above function in a Script editor. also, don't forget to provide your group name.
Besides, the above code, you can use the same endpoint _api/Web/CurrentUser/Groups
in your SPFX web part by using import { SPHttpClient } from '@microsoft/sp-http';
this.context.spHttpClient.get(this.context.pageContext.site.absoluteUrl + "_api/Web/CurrentUser/Groups",
SPHttpClient.configurations.v1)
.then((groupResponse: SPHttpClientResponse) => {
groupResponse.json().then((groupsData: any) => {
var groups = groupsData.value;
groups.forEach(group => {
if (group.Title == "**your group name**") {
// your code
}
});
});
});
2) Check if the current user is a member of a group using Microsoft Graph in SharePoint
You can use checkMemberGroups and user: getMemberGroups to return all the groups that the user is a member of.