14

I'm rebuilding a SP 2013-era EditForm.aspx web part using SPFx & React.

I would appreciate advice on how to get the query string into a SPFx web part.

I don't see any methods in the SharePoint Framework Reference; I apologize if I missed something.

I'm using React - its documentation leads to React-router, which seems overkill for just getting an item id, not to mention the struggle of changing the components at the root of the SPFx web part.

I've reviewed the PNP-JS-Core, and didn't find any help there either.

How are other people doing this?

1
  • 3
    Why not simply use pure JS to get the query string parameters from window.location.href? Or even simpler with window.location.search which gives you only the query string, but it is not supported below IE11 and some other old browser versions.
    – Mihail
    Commented Apr 28, 2017 at 13:54

4 Answers 4

8

spfx has some utility classes to help. start by

import {  UrlQueryParameterCollection } from '@microsoft/sp-core-library';

Then in your onRender:

 var queryParameters = new UrlQueryParameterCollection(window.location.href);
    if (this.properties.mode !== modes.NEW) {
      if (queryParameters.getValue("Id")) {
        const id: number = parseInt(queryParameters.getValue("Id"));
        let fields = "*,ParentTR/Title,Requestor/Title";
        // get the requested tr
        pnp.sp.web.lists.getByTitle("Technical Requests").items.getById(id).expand("ParentTR,Requestor").select(fields).inBatch(batch).get()
          .then((item) => {

I create a 'mode' property on the property pane to specify if the form is in new, edit or display mode. Throw an error if no id is specified in display or edit mode. this example uses pnp-js-core.

hth

1
  • 1
    'UrlQueryParameterCollection' is deprecated. Use the URLSearchParams browser API instead.
    – Raf
    Commented Sep 28, 2020 at 10:21
4

Thanks Mihail!

I copied Waldek's getLatestItemId method and added in the window.location.

I'm not going to pretend I know how Promises work, especially in TypeScript, but so far so good.

If the query string doesn't happen to have a number, then it returns a nice message saying to call me.

private getListItemId(): Promise<number> {
    let strLocationSearch: string = window.location.search.split("id=")[1];
    let numLocationSearch: number = parseInt(strLocationSearch);
    return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
        this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items(${numLocationSearch})?$select=id`,
            SPHttpClient.configurations.v1,
            {
                headers: {
                    'Accept': 'application/json;odata=nometadata',
                    'odata-version': ''
                }
            })
            .then((response: SPHttpClientResponse): Promise<{ Id: number }> => {
                return response.json();
            }, (error: any): void => {
                reject(error);
            })
            .then((response: { Id: number }): void => {
                if (response.Id === numLocationSearch) {
                    resolve(response.Id);
                }
                else {
                    resolve(-1);
                }
            });
    });
}
2

As UrlQueryParameterCollection is deprecated, I suggest to use the URLSearchParams browser API instead.

Here is my code to get value of search parameter:

const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
let searchParam: string;
params.has('search') ? searchParam = params.get("search") : searchParam = "";

Here is my code to delete search parameter and update URL:

const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
if (params.has('search')) {
  params.delete('search');
  window.history.replaceState({}, '', `${location.pathname}?${params}`);
}
2

To simplify more the answer by Raf, you can directly use the url.search like below. Here I am getting value of ID parameter.

const params = new URLSearchParams(window.location.search);
let val = params.get('ID');
console.log(val);

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.