Storagepipe Is Now Thrive

GridWay Is Now Thrive


SharePoint Framework – Passing The SharePoint Context Object

SharePoint Framework – Passing The SharePoint Context Object

The SharePoint context object can give you a lot of crucial information about the user currently logged in, the page that a user is on, templates being used, and more.

By default, when working in SharePoint Framework, by default, you will have access to the context object within the most parent component.

In this case, the component is the BaseClientSideWebPart component. For the most part, we will want to keep each component in our projects clean and, as we don’t have access to state in this component, we will want to pass context down to the next highest child component. This child component will technically become the parent component to every other component in our project as it will handle most of our data operations (this can also be a service if you would like).

Passing the Context Object Down

A very important use case for employing the context object is being able to utilize the spHttpClient that will grant us access to SharePoint’s REST API in the context of the currently logged in user.

The easiest way to do this is to pass the context object as a whole down as a member of props. When creating a project in SharePoint Framework (as a Web Part project), it will generate a main .ts file (the BaseClientSideWebPart) and a single component with the .tsx syntax.

In addition, a Props file for that .tsx file should also be available. We will first want to add a line to our Props file for the context object we will be passing. Simply define “context: any;” in the Props file, and we should be done here (as shown below).


Now that our Web Part has the property available, we can head over into our root .ts file to pass the context object down. To do so, simply define the prop “context: this.context” in the React.createElement statement (as shown below).


Our context object should now be available in our SPFXWebPart. To test this, we can make a simple REST API call to get the current site’s lists. Add the code shown below into the constructor statement of your web part (you may need to add the constructor if you did not already).

The site URL variable can either be defined or replaced with plain text. It can also be removed completely to make a relative call to the site it is deployed on.

If the call comes back with the expected data, you have successfully passed the SharePoint context object down through your web parts in SharePoint Framework.


Interested in this solution for your SharePoint investment and working with the Timlin team? Request a 30-minute free consultation here