Sharepoint - How to retrieve pageContext in SPFx?
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)
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