Hello SharePointers,

I hope you must enjoyed our previous blog on the Required toolchain to build SPFX web parts and extensions. Now in this article, we will learn to create an SPFX web part and access Microsoft teams into it.

SharePoint Framework: SPFX is a framework that helps you to build custom apps for your SharePoint modern sites and let you integrate them on classic site as well.

Why SharePoint Framework?

  • The controls are responsive and accessible by Nature.
  • Users can use any javascript framework like React, Angular, TypeScript, Handlebar and many more.
  • Users can use client development tools like npm. Yeoman, gulp, webpack, etc.

Now as we know what SharePoint Framework is, let us see what Microsoft Teams is.

Microsoft Teams:

Microsoft Teams is a communication tool that helps members of an organization to communicate effectively with conversational tabs. Easily schedule meetings, record calls and upload them on Microsoft Streams for later use.

Pre-requisites:

  • Visual Studio Code Installed
  • Node version 8.11.3
  • Gulp and Yeoman installed globally

Let’s Start;

Inside the command prompt create your project folder and switch to it.

Create Project Directory
create a project directory

then type below command in your terminal

"yo @microsoft/sharepoint",
yeoman command

This will prompt you with questions like,

  • What is your Solution name? <“give your solution name here”>
  • Which baseline packages do you want to target for your compinents? SharePoint Online
  • Where do you want to place the files? Use Current folder
  • Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites without running any feature deployments or adding any apps to a site? Yes
  • Will the components of the solution require permission to access web APIs that are unique and not shared with other components in a tenant? Yes
  • Which type of client-side component to create? Webpart
  • What is your web part name? TeamsInSP
  • What is your web part description? TeamsInSP Description
  • Which Framework would you like to use? React

Now, after all this please wait for some time yeoman will create a solution structure and gives you a confirmation message.

Yeoman confirmation message

Run “gulp serve” and check if your local host pops up.

Local host

now navigate to “https://yourtenant.sharepoint.com/layouts/15/workbench.aspx” search name of your web part and add it.

Workbench Webpart

after you’ve added your web part successfully, Now we can use Microsoft Graph API.

Microsoft Graph API: using Microsoft Graph API you can access the data of users present in Microsoft cloud.

Endpoint URL: https://graph.microsoft.com

We have used pnp/graph to call graph rest service.

before proceeding with the code, let’s check if the rest services workes properly.

for this, go to https://developer.microsoft.com/en-us/graph/graph-explorer

microsoft graph explorer

make sure to sign in with your office 365 account

Run a sample query to fetch all the MS Teams that you are connected by typing below URI.

https://graph.microsoft.com/v1.0/users./joinedTeams

Graph Queri URI

It will list all MS Teams of yours.

Reasult Tems Graph URI

Troubleshooting the Errors in Response

If you receive a 403 status code in response then don’t panic, just check the Graph API Permissions.

Enable below permissions and Approve.

  1. User.Read.All
  2. User.ReadWrite.All
  3. Group.Read.All
  4. Group.ReadWrite.All

Run a query again and now you will see a full response.

Now as our API is working fine, Let’s go ahead and integrate it with our SPFX.

TO Use Graph API in SPFX , run below command

npm install @pnp/graph –serve”

SPFX to Access Microsoft Teams

Move to your <solution name>webparts.ts file and import the library into your application, Update OnInit function and access the root SP object in render

import { graph } from "@pnp/graph";

export interface ITeamsInSpWebPartProps {
  description: string;
  context:any;
}

export default class TeamsInSpWebPart extends BaseClientSideWebPart<ITeamsInSpWebPartProps> {


  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
    graph.setup({
      spfxContext: this.context
    });
    });
  }
Now modify the render method to get all the teams and add another Batching function to loop through each teams properties and get its webUrl for redirection.

  public async render(): Promise<void> {
    let array = [];
    const myJoinedTeams = await graph.me.joinedTeams.get();
    this.domElement.innerHTML = `Loading...`;
    myJoinedTeams.map((res) => {
      array.push(this.Batching(res.id));
    });
    Promise.all(array).then((res)=>{
            this.domElement.innerHTML = `Groups: <ul>${
              res.map(g =>
          `<li><a href='${g.webUrl}'>${g.displayName}</a></li>`
        )
        .join("")
      }</ul>`;
    })
  }
  private async Batching(ID) {
    const team = await graph.teams.getById(`${ID}`).get();
    return team;
  }

if you switch to your workbench.aspx you can see a list of your teams being rendered on the DOM, oh click of each will take you to a particular team.

Teams

Hey, Congratulations 🙂 , we have got all our teams in SPFX. We will customize it to look more pleasant. Add a little bit of CSS to do a Magic.

SPFX to access MS teams

Deployment:

So far, we are running our application locally at “https://<tenant>.sharepoint.com/_layouts/15/workbench.aspx”, to move this to Production

Step1. go to your Package-Solution.json file inside config folder and insert the following piece of code.

"webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "User.Read.All"

      },
      {
        "resource": "Microsoft Graph",
        "scope":"User.ReadWrite.All"
      },
      {
        "resource": "Microsoft Graph",
        "scope": "Group.Read.All"

      },
      {
        "resource": "Microsoft Graph",
        "scope":"Group.ReadWrite.All"
      }
    ]
  },

These are the permissions enabled organization wide for our application to work properly.

Step2. do a “Gulp bundle –ship

Step3. And Finally, run “gulp package-solution –ship

Solution Deployment

You can upload the .sppkg file inside Sharepoint/solution folder to your app catalog.

Before adding this webpart to any site, switch to

https://<yourtenant>-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx#/home” and click API Management

Access MS TEAMS (Teams) in SPFX Web part

You can see the permissions that is required for our application in the being listed under “Pending Approvals”

Graph Permissions

Approve them and just add a webpart to your modern site and just play with it.

Congrats, We have successfully integrated our SPFX webpart with MS Teams.

The Complete solution looks like this.

Access MS TEAMS (Teams) in SPFX Web part

you can refer to this git hub article for specific API service according to your requirements.

For more such tutorials Please visit SharePoint Gems

8 thoughts on “Access MS TEAMS (Teams) in SPFX Web part”
  1. I’m the manager of JustCBD Store company (justcbdstore.com) and I am currently planning to broaden my wholesale side of company. It would be great if someone at targetdomain share some guidance . I considered that the best way to do this would be to connect to vape shops and cbd retailers. I was really hoping if someone could recommend a trusted web site where I can purchase CBD Shops B2B Sales Leads I am currently reviewing creativebeartech.com, theeliquidboutique.co.uk and wowitloveithaveit.com. Unsure which one would be the most ideal solution and would appreciate any support on this. Or would it be much simpler for me to scrape my own leads? Ideas?

Leave a Reply