Search code examples
spfxpagecontext

How to use the pageContext in SPFx?


I am trying to get a value from the current page by using the pageContext but I am getting either undefined or 404. This is the situation: In the Site pages library there are several news pages. Each news page has some tags attached to them. This tags lives in a custom column in the Site Pages library. There are news that have 1 tag and other several tags. It can be the situation where two or more news share the same tag(s). The goal is when I open a news page the tags that are attached to that news are also visible.

Until now I am using @pnp/pnpjs and the code looks like this:

var result: any = await sp.web.lists.getByTitle("Site Pages")
  .items.getById(15)
  .select("Tags")
  .get();

return await result.Tags;

And it is giving me 404 error

I also tried this one:

this.context.pageContext.list('Site Pages').listItem['Tags'].get().then((items: any[]) => {
  console.log(items);
});

But it giving me Cannot read property 'list' of undefined

Du you have an idea how can get the value of the Tags column asociated with the current news?

Here is an update Now I am getting the right tag. The question now is how to show it in the screen?

import * as React from 'react';
import styles from './ReadTags.module.scss';
import { IReadTagsProps } from './IReadTagsProps';
import { sp } from '@pnp/pnpjs';

export default class ReadTags extends React.Component<IReadTagsProps, {}> {
  constructor(props: IReadTagsProps) {
    super(props);

  }

  private async getTags() {
      var id = this.props.context.pageContext.listItem.id;
      var result: any = await sp.web.lists.getByTitle("Site Pages")
        .items.getById(id)
        .select("Tags")
        .get();

      return await result.Tags;
  }

  public render(): React.ReactElement<IReadTagsProps> {
    console.log(this.getTags());
    return (
      <div className={ styles.readTags }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

Regards Amerco


Solution

  • What you'll probably want to do is store your tags in the state of your component. Then you can show these (if the value from state is not empty) during your render. I can highly recommend working through the React tutorial to understand React lifecycle and state/props.

    https://reactjs.org/tutorial/tutorial.html

    https://reactjs.org/docs/state-and-lifecycle.html

    Something with getting your data in componentDidMount, storing it in the state by using this.setState and then running through them in render with this.state.tags. It's more of a React question then a SPFx question :)

    There's a ton of samples here with SPFx and React:

    https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples