PnP Modern Search Web Part: How Do I Customize It? - Global SharePoint (2024)

PnP Modern Search Web Part: How Do I Customize It? - Global SharePoint (1)

PnP Modern Search Web Part: In this tutorial, we will learn about how to develop a SharePoint Online custom search web part using the PnP JS and SharePoint Framework (SPFx).

Table of Contents

Key-Highlights: Develop custom search web part using PnP JS

  • What is PnP Modern Search Web Part in SharePoint Online?
  • Project scaffolding process
  • Launch Visual Studio editor
  • SearchService.ts file code
  • SpFxSearchWebPart.ts file (web part main file) code
  • Demo – SPFx framework search results using the PnP JS

What is PnP Modern Search Web Part in SharePoint Online?

Introduction

The PnP Modern Search Web Part is an innovative, open-source solution developed by the SharePoint Patterns and Practices (PnP) community. This web part significantly enhances the default search capabilities in SharePoint Online, offering users a highly customizable and powerful search experience. In this article, we’ll explore its features, benefits, and how to get started with the PnP Modern Search Web Part.

Key Features

  1. Customizable Search Box
    • The search box component allows users to input their search queries with ease. It can be customized to fit the look and feel of your SharePoint site.
  2. Advanced Search Results
    • The search results web part displays search results in a variety of customizable layouts. Users can tailor the display to show the most relevant information, such as title, summary, and metadata.
  3. Refiners and Filters
    • Refiners and filters help narrow down search results based on specific criteria, such as content type, date, or custom metadata. This functionality makes it easier for users to find exactly what they need.
  4. Search Verticals
    • Search verticals provide different search experiences for various types of content. For example, you can set up separate verticals for documents, people, or news, each with its own tailored search results page.
  5. Connectors and Data Sources
    • The PnP Modern Search Web Part supports integration with multiple data sources, including SharePoint lists, libraries, and external sources. This allows for a unified search experience across different repositories.

Benefits

  1. Enhanced User Experience
    • With its advanced features and customization options, the PnP Modern Search Web Part significantly improves the user experience by providing more relevant and accessible search results.
  2. Flexibility and Customization
    • The web part’s flexibility allows administrators and developers to customize the search experience to meet the specific needs of their organization.
  3. Open Source and Community-Driven
    • Being an open-source project, it benefits from continuous improvements and updates from the PnP community, ensuring it stays current with the latest trends and requirements.
  4. Seamless Integration
    • The web part integrates seamlessly with modern SharePoint sites, enhancing their functionality without compromising performance.

Getting Started

  1. Installation
    • To get started, download the PnP Modern Search Web Part from the GitHub repository and follow the installation instructions provided.
  2. Configuration
    • Once installed, configure the web part according to your requirements. This includes setting up the search box, search results layout, refiners, filters, and connecting to data sources.
  3. Customization
    • Customize the web part using the extensive configuration options available. You can modify the appearance, behavior, and functionality to match your organizational needs.
  4. Deployment
    • Deploy the configured web part to your SharePoint Online site. Ensure that it meets your performance and usability standards through thorough testing.

Project scaffolding process: Develop custom search web part using PnP JS

Create a folder name “SPFx_Search”.

Navigate to the above created folder.

Enter the below parameters when asked:

Let's create a new SharePoint solution.? What is your solution name? sp-fx-search? Which baseline packages do you want to target for your component(s)? SharePoint Online only (latest)? Where do you want to place the files? Use the current folderFound npm version 6.14.7? Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately withoutrunning any feature deployment or adding apps in sites? No? Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? No? Which type of client-side component to create? WebPartAdd new Web part to solution sp-fx-search.? What is your Web part name? SPFx_Search? What is your Web part description? SPFx_Search description? Which framework would you like to use? (Use arrow keys)> No JavaScript frameworkReactKnockout

Then we will get the below screen:

We will need to install SharePoint PnP and Office UI Fabric React to our project, now run the following commands in sequence:

npm install sp-pnp-js --savenpm install office-ui-fabric-react --save

The above two commands will install and save the required files in the project. We can see all dependencies in the package.json file.

"dependencies": {"@microsoft/sp-client-base": "~1.0.0","@microsoft/sp-core-library": "~1.0.0","@microsoft/sp-webpart-base": "~1.0.0","@types/webpack-env": ">=1.12.1 <1.14.0","office-ui-fabric": "^2.6.3","sp-pnp-js": "^2.0.2"},

Launch Visual Studio editor: Develop custom search web part using PnP JS and SPFx

Open the project code in the visual studio editor by typing the “code .” command.

Create SearchService.ts file with the two classes MockSearchService (for the mockup search test)and SearchService (for actual Sharepoint Online search test).

SearchService.ts file code:

'usestrict';import*aspnpfrom'sp-pnp-js';exportinterfaceISearchResult{link:string;title:string;description:string;author:string;}exportinterfaceISearchService{GetMockSearchResults(query:string):Promise<ISearchResult[]>;}export class MockSearchService implements ISearchService{public GetMockSearchResults(query:string) : Promise<ISearchResult[]>{return new Promise<ISearchResult[]>((resolve,reject) => { resolve([{title:'This is test title 1',description:'Test Title 1 description',link:'globalsharepoint2020.sharepoint.com Jump ',author:'Global SharePoint1'},{title:'This is test title 2',description:'Test Title 2 description',link:'globalsharepoint2020.sharepoint.comJump ',author:'Global SharePoint2'},]);});}}export class SearchService implements ISearchService{publicGetMockSearchResults(query:string):Promise<ISearchResult[]>{ const _results:ISearchResult[] = [];returnnewPromise<ISearchResult[]>((resolve,reject)=>{pnp.sp.search({Querytext:query,RowLimit:20,StartRow:0}).then((results)=>{results.PrimarySearchResults.forEach((result)=>{_results.push({title:result.Title,description:result.HitHighlightedSummary,link:result.Path,author:result.Author});});}).then(()=>{resolve(_results);}).catch(()=>{reject(newError("Error"));});});}}

Now open the SpFxSearchWebPart.ts file (web part main file):

SpFxSearchWebPart.ts file (web part main file)code:

'usestrict';import{Version,Environment,EnvironmentType}from'@microsoft/sp-core-library';import{IPropertyPaneConfiguration,PropertyPaneTextField}from'@microsoft/sp-property-pane';import{BaseClientSideWebPart}from'@microsoft/sp-webpart-base';import{escape}from'@microsoft/sp-lodash-subset';importstylesfrom'./SpFxSearchWebPart.module.scss';import*asstringsfrom'SpFxSearchWebPartStrings';import*aspnpfrom'sp-pnp-js';import*asSearchServicefrom'./Services/SearchService';import{SPComponentLoader}from"@microsoft/sp-loader";exportinterfaceISpFxSearchWebPartProps{description:string;}exportdefaultclassSpFxSearchWebPartextendsBaseClientSideWebPart<ISpFxSearchWebPartProps>{publicconstructor(){super();SPComponentLoader.loadCss("https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.2.0/css/fabric.min.cssJump");SPComponentLoader.loadCss("https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.2.0/css/fabric.components.min.cssJump");}publicrender():void{this.domElement.innerHTML=`<divclass="${styles.spFxSearch}"><divclass="${styles.container}"><divclass="ms-Grid-rowms-bgColor-themeLightms-fontColor-white${styles.row}"><divclass="ms-Grid-colms-u-lg10ms-u-xl8ms-u-xlPush2ms-u-lgPush1"><div><spanclass="ms-font-xlms-fontColor-white">${escape(this.properties.description)}</span><br/><divclass="ms-Grid"><divclass="ms-Grid-row"><divclass="ms-Grid-colms-u-sm10"><inputclass="ms-TextField-field"id="txtInput"placeholder="Search..."/></div><divclass="ms-Grid-colms-u-sm2"><Buttonclass="ms-Buttonms-Button--primary"id="btnSearchQuerySubmit"type="submit"value="Submit">Search</Button></div></div></div><divclass="ms-Listms-Grid-colms-u-sm12"id="searchResultsDisplay"></div></div></div></div></div></div>`;this.EventListners();}privateEventListners():void{constbtnSearch=this.domElement.querySelector("#btnSearchQuerySubmit");constqueryText:HTMLElement=<HTMLInputElement>this.domElement.querySelector("#txtInput");btnSearch.addEventListener('click',()=>{(newSpFxSearchWebPart()).OnChangeEvent(queryText);});}publicOnChangeEvent(text:HTMLElement):void{(newSpFxSearchWebPart()).renderSearchResults((<HTMLInputElement>text).value).then((html)=>{constelement=document.getElementById("searchResultsDisplay");element.innerHTML=html;});}privaterenderSearchResults(query:string):Promise<string>{const_search:SearchService.ISearchService=Environment.type==EnvironmentType.SharePoint?newSearchService.SearchService():newSearchService.MockSearchService();letresultsHtml:string='';returnnewPromise<string>((resolve)=>{if(query){_search.GetMockSearchResults(query).then((results)=>{results.forEach((result)=>{resultsHtml+=`<divclass=""ms-ListItemms-Grid-colms-u-sm8"><ahref="${result.link}"><spanclass="ms-ListItem-primaryText">${result.title}</span></a><spanclass="ms-ListItem-secondaryText">${result.author}<span><spanclass="ms-ListItem-tertiaryText">${result.description}</span><spanclass="ms-ListItem-metaText">10:15a</span><divclass="ms-ListItem-actions"><divclass="ms-ListItem-action"targerUrl="${result.link}"><iclass="ms-Iconms-Icon--OpenInNewWindow"></i></div></div></div>`;});}).then(()=>{setTimeout(()=>{constaction:HTMLCollectionOf<Element>=document.getElementsByClassName("ms-ListItem-action");for(leti=0;i<action.length;i++){action[i].addEventListener('click',(e)=>{window.open((e.currentTargetasElement).getAttribute("TargerUrl"));});}},300);resolve(resultsHtml);});}else{resultsHtml+="Pleaseprovidesearchqueryinputinsearchbox.....";resolve(resultsHtml);}});}protectedgetdataVersion():Version{returnVersion.parse('1.0');}protectedgetPropertyPaneConfiguration():IPropertyPaneConfiguration{return{pages:[{header:{description:strings.PropertyPaneDescription},groups:[{groupName:strings.BasicGroupName,groupFields:[PropertyPaneTextField('description',{label:strings.DescriptionFieldLabel})]}]}]};}}

Demo – SPFx framework search results using the PnP JS (PnP Modern search)

Run the web part using the gulp serve command.

Then add the web part to the workbench.html page.

Pass “Test” as search text, then hit the “Search” button, we can see the search result which was defined in the SearchService.ts file as mockup data.

Now, let’s add the same web part to the SharePoint Online page, for example – “globalsharepoint2020.sharepoint.com/_layouts/15/workbench.aspx.”

Then pass “Global” as search text, hit on the “Search” button, and now we can see the search results from the actual SharePoint Online tenant which matches the “Global” keyword.

Summary: Develop custom search web part using PnP JS and SPFx

Thus, in this article, we have learned about how to develop a SharePoint Online custom search web part using the PnP JS and SharePoint Framework (SPFx).

The PnP Modern Search Web Part is a powerful tool for enhancing the search capabilities of SharePoint Online. Its advanced features, customization options, and seamless integration make it an invaluable addition to any SharePoint environment. By following the best practices outlined in this article, you can leverage the full potential of this web part and ensure your content ranks well in search engine results.

Source Code: PnP modern search using SPFx

The above source code can be downloaded from here.

See Also: SharePoint Online SPFx Articles

You may also like the below SharePoint SPFx articles:

  • SharePoint Online: CRUD operations using SPFx and PnP JS
  • SharePoint Online: Use theme color in SharePoint SPFx framework web part
  • SharePoint Online: CRUD operations using SPFx ReactJS framework
  • SharePoint Online: CRUD operations using SPFx no javascript framework
  • Develop your first hello world web part in sharepoint framework (SPFx)
  • Understanding solution structure in SharePoint framework (SPFx)
  • Create custom property in SharePoint Framework – SPFx web part pane
  • Get list items from SharePoint using SPFx framework(No Javascript Framework)
  • Custom search result page in SharePoint Online – SPFx PnP Modern Search solution

About Post Author

SP Doctor

I am your SharePoint and Power Platform doctor and guide. Sharing knowledge with my fellow colleagues, friends, and the tech community makes me utmost happy in my job.

See author's posts

Related

PnP Modern Search Web Part: How Do I Customize It? - Global SharePoint (2024)
Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5785

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.