Sitecore Search SDK Integration [Part 1]

In today's web development landscape, delivering efficient and intuitive search functionality is crucial to provide an enhanced user experience for your visitors. With the advent of Sitecore Search, developers now have a powerful tool at their disposal to seamlessly integrate robust search capabilities into their Next.js applications.

Sitecore Search offers a comprehensive platform that allows you to incorporate predictive and personalized search experiences for your visitors. By leveraging the capabilities of Sitecore Search, you can request and retrieve data such as search results, facets, suggestions, and more, empowering you to build a highly tailored and relevant search experience.

Understanding the React SDK

What is the React SDK?

The React SDK from Sitecore Search is tailor-made for developers in the React ecosystem, including Next.js. It simplifies the integration of Sitecore Search into web apps, enriching the user experience with advanced search features. Developers can quickly enhance their applications with predictive search, personalized results, and more, thanks to the streamlined capabilities of the React SDK.

Key Components of the React SDK

The React SDK comprises two npm packages:

  1. React Package: This package forms the foundation of the SDK, providing core functionality.

  2. UI Package: Housing a plethora of UI components, the UI package equips developers with various composable to construct diverse user experiences seamlessly.

Getting Started with the React SDK

Installation and Configuration

To start utilizing the React SDK, we need to follow these fundamental steps:

  1. Install the two required npm packages: React Package and UI Package.
1npm install --save @sitecore-search/react
2npm install --save @sitecore-search/ui	
  1. Wrap the React application with the Widget Provider component, furnishing the SDK with essential functionality, usually in Next JS application _app.tsx file is the root of the application.
1<WidgetsProvider
2			env={process.env.NEXT_PUBLIC_SEARCH_ENV as any}
3			customerKey={process.env.NEXT_PUBLIC_SEARCH_CUSTOMER_KEY}
4			apiKey={process.env.NEXT_PUBLIC_SEARCH_API_KEY}
5			publicSuffix={true}>
6	<Component  {...rest}  />
7</WidgetsProvider> 
  1. Configure the Search Config object to establish the connection between the application and the designated search instance. It's recommended to store sensitive information, such as API keys, in environment variables for security purposes.
1NEXT_PUBLIC_SEARCH_CUSTOMER_KEY=<customer-key>
2NEXT_PUBLIC_SEARCH_API_KEY=<api-key>
3NEXT_PUBLIC_SEARCH_ENV=prod

Building Search Functionality with the React SDK

Creating Search Components

Once the SDK is integrated into the React application, we can start building out search functionality, in order to communicate with Sitecore Search API we will use query hooks available in the JS SDK package, for search results we will be using useSearchResults query hook, this hook is used request and retrieve data for search results widgets. page, keyphrase, selectedFacets, itemsPerPage, and sortType.

Following is the basic example of its utilization:

1import type { SearchResultsInitialState, SearchResultsStoreState, SearchResultsWidgetQuery } from '@sitecore-search/react';
2import { WidgetDataType, useSearchResults, useSearchResultsSelectedFacets, widget } from '@sitecore-search/react';
3
4type ArticleModel = {
5  id: string;
6  type?: string;
7  title?: string;
8  name?: string;
9  subtitle?: string;
10  url?: string;
11  description?: string;
12  content_text?: string;
13  image_url?: string;
14  source_id?: string;
15};
16
17type ArticleSearchResultsProps = {
18  defaultSortType?: SearchResultsStoreState['sortType'];
19  defaultPage?: SearchResultsStoreState['page'];
20  defaultItemsPerPage?: SearchResultsStoreState['itemsPerPage'];
21  defaultKeyphrase?: SearchResultsStoreState['keyphrase'];
22};
23
24type InitialState = SearchResultsInitialState<'itemsPerPage' | 'keyphrase' | 'page' | 'sortType'>;
25
26export const SearchResultsComponent = ({
27  defaultSortType = 'date_desc',
28  defaultPage = 1,
29  defaultKeyphrase = '',
30  defaultItemsPerPage = 10,
31}: ArticleSearchResultsProps) => {
32  const {
33    widgetRef,
34    actions: {
35      onResultsPerPageChange,
36      onPageNumberChange,
37      onItemClick,
38      onFilterClick,
39      onSortChange,
40      onFacetClick,
41      onClearFilters,
42    },
43    state: { sortType, page, itemsPerPage },
44    queryResult: {
45      isLoading,
46      isFetching,
47      data: {
48        total_item: totalItems = 0,
49        sort: { choices: sortChoices = [] } = {},
50        facet: facets = [],
51        content: articles = [],
52      } = {},
53    },
54  } = useSearchResults<ArticleModel, InitialState>({
55    query: (query:SearchResultsWidgetQuery) => query,
56    state: {
57      sortType: defaultSortType,
58      page: defaultPage,
59      itemsPerPage: defaultItemsPerPage,
60      keyphrase: defaultKeyphrase,
61    },
62  });
63  const totalPages = Math.ceil(totalItems / itemsPerPage);
64  const selectedSortIndex = sortChoices.findIndex((s:any) => s.name === sortType);
65  const selectedFacetsFromApi = useSearchResultsSelectedFacets();
66  if (isLoading) {
67    return ( <div> ... </div> );
68  }
69  return ( <div ref={widgetRef}> ... </div> );
70};
71
72const SearchResultsStyledWidget = widget(SearchResultsComponent, WidgetDataType.SEARCH_RESULTS, 'content');
73
74export default SearchResultsStyledWidget;
75

in the above code line #69 is where our UI will be placed to create search experience like the implementation of facets, search results, pagination, we will disuss this in the next parts of the blog.

It is important to Convert a UI component into a widget component before adding it to pages or use.

To convert a component into a widget component, pass the UI component to the widget

Utilizing Supporting Resources

Documentation and Sample Repositories

Sitecore Search offers a comprehensive suite of resources to help developers in their journey to develop search experience:

  1. Detailed SDK documentation and a Storybook instance for exploring UI components.

https://developers.sitecorecloud.io/search-sdk/react/latest/storybook/index.html?path=/story/introduction-introduction--page

  1. Sample repositories, including a starter kit and the Developer Portal repository, provide practical examples and insights.

https://github.com/Sitecore/Sitecore-Search-JS-SDK-Starter-Kit

Conclusion

Incorporating Sitecore Search into React applications empowers developers to deliver enhanced search experiences, thereby elevating user satisfaction and engagement. By leveraging the React SDK and its accompanying resources, developers can streamline the implementation process and unlock the full potential of search functionality within their applications.

In the next blog post, I'll show you how to use the Sitecore Search SDK Starter Kit from GitHub repo to our Sitecore Next.js solution. Stay tuned for simple steps to create a great search experience!

Related Posts

Leveraging Sitecore Search SDK Starter Kit into Your Sitecore Next.js Solution [Part 2]

In this blog post, I'll walk you through the process of smoothly leveraging the Search SDK Starter Kit into a Sitecore Next.js solution. ## Prerequisites Before proceeding, ensure the following prer

Read More

Sitecore Search SDK Integration [Part 1]

In today's web development landscape, delivering efficient and intuitive search functionality is crucial to provide an enhanced user experience for your visitors. With the advent of Sitecore Search,

Read More

Sitecore Search SDK Starter Kit: Enhanced User Experience

The Sitecore Search SDK Starter Kit provides a powerful foundation for developers to build robust and user-friendly search functionalities into their websites. This open-source project offers a signi

Read More