SharePoint Framework: Retrieve SharePoint Search Results using webpart
In this section, we will try to work with SharePoint Search and retrieve the search results based on a keyword using SPFx and PnP JS
Create the Web part Project
Spin up Node.js command prompt, using which we will be creating the Web part project structure.We can create the directory, where we will be adding the solution, using the command given below.
md RetrieveSearchResults
Let’s move to the newly created working directory, using the command.
cd RetrieveSearchResults
We will then create the client Web part by running the Yeoman SharePoint Generator.
yo @microsoft/sharepoint
Install the PnP module using NPM as :
npm install @pnp/sp@1.3.8 @pnp/odata@1.3.8 @pnp/logging@1.3.8 @pnp/common@1.3.8
The generated project structure will look like below
Retrieve Search Results
We can reference the PnP js file in the project by including the below line to the top of the TS file
import * as pnp from '@pnp/sp'
import { SearchQuery, SearchResults} from "@pnp/sp";
We can get the search results using the below function. Here we will be using PnP method, ‘pnp.sp.search’ which accepts the search keyword as the parameter. It will return the search results which we will display as a table.
1. private GetSearchresults(): void { 2.
pnp.sp.search("SharePoint").then((result : SearchResults) => {
var props = result.PrimarySearchResults;
debu gger; 6.
var propValue = "";
var counter = 1;
props.forEach(function(object) {
propValue += counter++ +'. Title - ' +object.Title +"<br/>"+"Rank - " + object.Rank
+"<br/>"+"File Type - " + object.FileType+"<br/>"+ "Original Path - "
+object.OriginalPath +"<br/>"+" Summary - "+ object.HitHighlightedSummary + "<br/>"+"<br/>";
11. });
document.getElementById("spSearchresults").innerHTML = propValue;
}).catch(function(err) {
console.log("Error: " + err); 15. });
16.
17. }
TS File contents for displaying the retrieved search results
The entire TS file contents is as shown below, ‘this.GetSearchresults()’ in the render method will call the function that will retrieve the search results based on the keyword. It will be then displayed within the div element declared in the render method.
import * as pnp from 'sp-pnp-js';
import { SearchQuery, SearchResults } from "sp-pnp-js"; 3.
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base'; 10.
11. import { escape } from '@microsoft/sp-lodash-subset'; 12.
13. import styles from './RetrieveSearchResults.module.scss';
14. import * as strings from 'RetrieveSearchResultsWebPartStrings';
15. import * as pnp from '@pnp/sp'
16. import { SearchQuery, SearchResults} from "@pnp/sp";
17. import { IRetrieveSearchResultsWebPartProps } from './IRetrieveSearchResultsWebPartProps';
18.
19. export default class RetrieveSearchResultsWebPart extends BaseClientSideWebPart<IRetrieveSearchResultsWebPartProps> {
20. private GetSearchresults(): void { 19.
20.
pnp.sp.search("SharePoint").then((result : SearchResults) => {
21. var props = result.PrimarySearchResults;
22. debugger; 23.
var propValue = "";
var counter = 1;
props.forEach(function(object) {
propValue += counter++ +'. Title - ' +object.Title +"<br/>"+"Rank - " + object.Rank
+"<br/>"+"File Type - " + object.FileType+"<br/>"+ "Original Path - "
+object.OriginalPath +"<br/>"+" Summary - "+ object.HitHighlightedSummary + "<br/>"+"<br/>";
28. });
document.getElementById("spSearchresults").innerHTML = propValue;
}).catch(function(err) {
console.log("Error: " + err); 32. });
33.
34. } 35. 36.
37. public render(): void { 38.
this.domElement.innerHTML = `
<div class="${styles.helloWorld}">
41. <div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
44. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to SharePoint Framework Development using PnP JS Library</span>
45.
46. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve SharePoint Search Result</p>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
50. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">Search Results </div>
<br>
52. <div id="spSearchresults" />
</div>
54. </div> 55. </div>`;
56. this.GetSearchresults();
57. } 58.
protected get dataVersion(): Version {
return Version.parse('1.0');
61. } 62.
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
66. {
header: {
description: strings.PropertyPaneDescription 69. },
70. groups: [
71. {
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
76. })
77. ]
78. }
79. ]
80. }
81. ]
82. };
83. }
84. }
Test the Web part in SharePoint Online
Now, let’s test the Web part in SharePoint Workbench available in SharePoint Online. Once we have login in to SharePoint Online, we can invoke the workbench by appending the text ‘_layouts/15/workbench.aspx’ to SharePoint Online URL. Add the webpart to the page by selecting ‘RetrieveSearchResults’ icon.
Thus, the search results have been retrieved and it has been listed in the web part as shown below.
Download
The major project files used in this solution has been zipped and uploaded at Microsoft TechNet Gallery.
Feel free to download it.