4

I'm following the second tutorial from the SharePoint Framework dev center:

Connect to SharePoint

It states that you can retrieve details from this.context.pageContext, however this is no longer the case with the GA (1.0.0) release as the codebase has changed, and the documentation and tutorials haven't been updated to reflect this. The documentation seems to point to either IWebPartContext, or PageContext, but I'm just a little lost on how exactly to retrieve the page context from the component (webparts\helloWorld\components\HelloWorld.tsx).

Could someone shed some light on the new method for going about this?

10

this.context.pageContext is available on render() method within top level class that extends BaseClientSideWebPart. Simply pass this.context as a props of to HelloWorld.tsx to reuse it.

Sample (HelloWorldWebpart.ts):

public render(): void {
const element: React.ReactElement<any > = React.createElement(
   HelloWorld,
   {
     description: this.properties.description,
     context: this.context
   }
);

 ReactDom.render(element, this.domElement);
}

And in HelloWorld.tsx you should be able to retrieve the context as this.props.context

Or alternatively use react redux to store the context on initialization onInit() method (https://dev.office.com/sharepoint/reference/spfx/sp-webpart-base/oninit-baseclientsidewebpart)

  • 1
    Thank you! This is all I was looking for. To any one else that stumbles on this: I was able to get this working by simply adding context: any; to my component props file and passing it as Jonathan mentioned above. – DivXZero Mar 29 '17 at 13:38
1

It is better to use correct type WebPartContext instead of any. Don't forget to put namespace.

import { WebPartContext } from '@microsoft/sp-webpart-base';

export interface WebPartProps {
   context: WebPartContext;
   description: string;
}
...

public render(): void {
   const element: React.ReactElement<WebPartProps> = React.createElement(
   HelloWorld,
   {
     description: this.properties.description,
     context: this.context
   }
);

 ReactDom.render(element, this.domElement);
}

Here is more info WebPartContext class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.