2

Ok so i've searched for a while and tried everything. I've followed these steps as well -> How to retrieve pageContext in SPFx?

So far its just a "testing phase", but i get stuck at the beginning since i cant get to the SP context.

This is what i've tried for testing ->

{escape(this.context.pageContext.web.title)}

And i'm getting "cant get property web of undefined".

Any idea?

2
  • Where is this code? I see you tagged this with react. Is this code in your main webpart class or in a react component? Commented Sep 10, 2018 at 18:47
  • The code that i posted in my question is located in the main webpart TSX. To be more exact its where you edit how the webpart looks. By default it contains return ( <div className={ styles.WEBPARTNAME}> Hopefully you can understand from my "amazing" explanation.
    – Dante R.
    Commented Sep 10, 2018 at 19:06

2 Answers 2

2

Old reply, but someone is bound to run into the same error.

When you're passing the context as a prop in the base WebPart, make sure you're passing it by using the this.context.

Passing the WebPartContext prop from the base web part component to the child component:

export default class SpTestAppWebPart extends BaseClientSideWebPart {

  public render() {
    const element = React.createElement(
      SpTestApp,
      {
        description: this.properties.description,
        ctx: this.context
      }
    );
  }

Then inside the child component, you should be able to use the WebPartContext on the props passed to it:

export default class SpTestApp extends React.Component {

  public render() {
    return (
      <div className={ styles.spTestApp }>
        <div className={ styles.container }>
            <p>{this.props.ctx.pageContext.web.absoluteUrl}</p>          
          </div>
        </div>
      </div>
    );   
  }
}
1

If you're in the TSX then you're in the component, not the web part. A component is a dumb rendering construct. All your logic should be dealt with inside the web part itself, passing data to the component.

I don't like the way the SPFX tooling puts components in the same folder as web parts. It exacerbates misunderstandings like this. A much better architecture in my opinion would be to have a separate top level components folder.

1
  • I am already passing the context to the Component through props (same as the default description prop). However...it says its undefined. So there is either a bug with React SPFX or i'm not passing the context correctly (tho i get no compilation errors or whatever).
    – Dante R.
    Commented Sep 10, 2018 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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