Join Bridgewater State University for a Website Search Webinar on Dec. 10 | REGISTER NOW

December 06, 2023

Kevin Montgomery

|

7 min. read

Build engaging site search with SearchStax Site Search and Search UI Components for React

With the recent release of Search UI Kit it’s even easier to build engaging and effective site search functionality in a dynamic front end or native app. SearchStax Site Search already includes site search REST APIs – but our new Search UI Components for React handle backend interaction and authentication so you can start building without having to implement another API.

Let’s look at how to rebuild our own SearchStax Site Search Documentation site into a React and Drupal-powered headless platform including site search. Here are the different platforms, frameworks, and modules used in the build.

  • SearchStax Site Search – Site Search handles content indexation and search as well as the API for the Search UI Components
  • Drupal – The Drupal CMS will power the content management workflow
  • JSON:API – The JSON:API modules will expose basic site navigation and content to the front end
  • React – The React front end will handle user navigation request and render the interface and content
  • Material UI – MUI components streamline UI development and theming

You can build your own headless environment by cloning our SearchStax Docs Headless repo. This repo includes a Docker environment for Drupal and React development that’s preloaded with the headless front end and Drupal instance with documentation content.

Why Go Headless with Drupal and React?

React has become one of the dominant front end frameworks especially when delivering dynamic and engaging front end experiences. While building with React can be quicker and offer highly interactive interfaces –  it lacks many of the core features needed to deliver “standard” static website content like those of Drupal, WordPress, Sitecore, and other content management systems. Like many front end frameworks, React is often backed by a REST or GraphQL backend that delivers highly structured JSON as opposed to fully formatted HTML.

Going headless with your CMS, however, can give you the publishing features of a CMS without the drawbacks of server side state management and rendering. Your development team can deliver better features with higher release velocity by decoupling content editing and front end feature deployment so that both processes can proceed at their own pace.

Let’s take a look at how Drupal and React can work together along with SearchStax Site Search for an interactive and easy to manage technical documentation site.

Information Flow between Drupal, React, and SearchStax Site Search

Going headless typically means that the front end will need to manage user state separately from the back end (as opposed to using parameters, cookies, request headers, or other methods to indicate user state during a URL request). Using the JSON:API module with Drupal exposes several endpoints for site menus and navigation, URL aliases, and nodes of content.

When the React app initially loads it’ll request the various menus from Drupal as well as the URL aliases so that it can build the base site navigation and then load the appropriate content for the requested URL. React can then request the full page content, process any inline tags, and render and update the interface.

SearchStax Site Search can index content from Drupal via the native integration and also supports crawling so other content sources and sites can be included in the index. Site search features can be built in React using our Search UI Components so site search features can be used and shown throughout the app.

Decoupling Drupal – Headless with JSON:API

Drupal is an excellent platform for backing a headless site since it offers easy editing, menu building, and high availability to act as your content API for your front end. Content editors can still securely access and edit content within Drupal and configure site navigation with menus with updates immediately available in the React front end.

Using the Drupal APIs for content and site configuration simplifies the front end and avoids having to hardcode things like link text, URLs, or long form content.

  • Menus – Main navigation, footer, and other site menus can be managed and updated in Drupal. The React app can be configured to fetch the appropriate menus for the various page components as needed.
    drupalsite.com/jsonapi/menu_link_content/menu_link_content
  • URL Aliases – Using react-router-dom in React can enable customized URL handling and navigation so that your front end behaves as expected when requesting a URL. Drupal content is has internal Drupal IDs that are mapped to human-readable URL aliases (e.g. /blog/updates/headless).
  • Page Content – Drupal content is accessed via Drupal ID when using the API so the React app will need to look up the URL alias to find the appropriate node ID and then request the page content.

Content Indexing

SearchStax Site Search integrates natively with Drupal so search indexes are updated immediately when content is added or updated. SearchStax Site Search includes search customization including customized relevance modeling, auto complete and related search suggestions, search faceting, filtering, and sorting, and analytics. These features are all directly implemented in the Search UI Components for Reach package and can be completely customized, styled, and extended in React.

Contentful React

React encourages reusability and component-based development that differs from fully formatted server-side rendered HTML that was simply injected into an area of a webpage. React does not easily allow loading HTML from an API into a component due to security issues as well as potential interference when rendering or responding to the virtual DOM.

Using the html-to-react package allows interception of specific HTML tags from the Drupal API so that they can be essentially modified into React components. This addresses any issues with malformed HTML and ensures that React is fully aware of all elements that exist within the app.

Basic Components

The React app in our example follows similar conventions to Drupal’s block layout – main navigation, left hand sub-navigation, and site footer wrapped around page content.

App

The root App component will establish the basic layout and routing for the React app. It will load site menus and URL aliases for basic rendering of site or global navigation (e.g. header or footer).
				
					
    <div className="App">
      <ThemeProvider theme={theme}>
        <AppBar position="fixed">
          <Toolbar>
            <Link to="/">
              <Box
                component="img"
                src="https://www.searchstax.com/wp-content/uploads/2022/02/logo.svg"
              />
            </Link>
            <SiteNav />
            <SearchBar section={section} />
          </Toolbar>
        </AppBar>
          <Routes>
            <Route path="/">
              <Route index element={<Docs url="/home" navMenu={navMenu} section={section} />} />
              <Route path="search" element={<Search />} />
              <Route path="*" element={<Docs url={location.pathname} navMenu={navMenu} section={section} />} />
            </Route>
          </Routes>
        <Footer />
      </ThemeProvider>
    </div>
				
			

Search Results using Search UI Components

Since site search is a universal feature it can be shown throughout the app. Search inputs can be included in the global navigation or footer. Search results can also be shown as a global overlay so that it’s available on every page.
				
					
<SearchstaxWrapper
  searchURL={config.searchURL}
  suggesterURL={config.suggesterURL}
  trackApiKey={config.trackApiKey}
  searchAuth={config.searchAuth}
  initialized={() => {}}
  beforeSearch={beforeSearch}
  afterSearch={afterSearch}
  authType={config.authType}
  router={{ enabled: true }}
  language={config.language}
>
  <Stack spacing={1}>
    <InputWidget />
    <RelatedSearchesWidget />
    <Stack direction="row">
      <OverviewWidget />
      <SortingWidget />
    </Stack>
    <Stack direction="row">
      <FacetsWidget />
      <Stack>
        <ExternalPromotionsWidget />
        <ResultWidget />
      </Stack>
    </Stack>
    <PaginationWidget />
  </Stack>
</SearchstaxWrapper>
				
			

Page

The Page component will watch for URL updates and find the appropriate node ID from the URL aliases and then request the page content. If the requested URL is not mapped to a specific Drupal page it can either be ignored or processed as a normal URL request (outside of React). Depending on site configuration the front end may need to load additional menus, tags, blocks, fields, or other elements.
				
					void fetchArticleFromID(drupalPath.attributes.path.replace('/node/','')).then((data: article) => {
  document.title = data.data[0].attributes.title;

  const htmlInput = data.data[0].attributes.body.value;
  const isValidNode = () => { return true; };
  const processNodeDefinitions = ProcessNodeDefinitions();
  const processingInstructions = [
    {
      shouldProcessNode: (node: any) => { return node.name && node.name === 'a'; },
      processNode: (node: any, _children: any, index: number) => {
        return React.createElement(React.Fragment, {key: index,}, [
          <a
            key={index}
            href={node.attribs.href}
            onClick={(e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => { handleLink(e, node.attribs.href); }}
          >{node.children[0].data}</a>
        ]);
      }
    },
    {
      shouldProcessNode: () => { return true; },
      processNode: processNodeDefinitions.processDefaultNode,
    },
  ];
  setReactContent(Parser().parseWithInstructions(htmlInput, isValidNode, processingInstructions));
});
				
			

Drupal and React Components

Using html-to-react allows for HTML content and formatting to live in Drupal itself while still rendering correctly in React. The html-to-react module also allows for interception of specific HTML tags from Drupal for modification in React.

Benefits and Drawbacks

While headless sites are inherently more complex they do offer some benefits that monolithic CMSs can’t match.

Headless Benefits

  • Dynamic features can be easier to develop especially with front end frameworks like React that abstract away much of the state management and browser compatibility issues that plagued JavaScript and jQuery front ends
  • Highly interactive experiences can respond faster by processing more data and user state in the front end instead of making a request to the back end and waiting for a fully rendered response
  • Content teams can still use CMS features such as drafts, authoring, and backups without relying on front end developers or pushing new code for content changes
  • Different front end designs or experiences (e.g. desktop, mobile, large-format displays) can consume and display the same content
  • Simplified backend with better performance since rendering and other custom modules are no longer needed to process each URL request
  • Reduced security footprint for Drupal
  • Site search becomes an integral site feature instead of a stand-alone page

Headless Drawbacks

  • More points of failure when relying on APIs for basic app functionality
  • May need to manage and maintain more than one server/environment for Drupal and React
  • Initial response time may be higher when loading React
  • May still need a server-side rendering solution (either Drupal or Server Side Rendering) for static content and search indexation

Is Headless right for my site?

Moving to headless can be driven by many factors including enhanced features or interactivity, full featured “app” experiences, interacting and consuming data from multiple servers or sources, as well as availability on many different screen and device types.

Next Steps

Search UI Components for SearchStax Site Search are available for ReactVueAngular, and other JavaScript-powered front end frameworks so developers can get started today testing and building accessible site search for headless apps.

What is React?

React is a JavaScript-powered front end framework. React allows front end developers to build dynamic and reactive user interfaces with reusable components.

What are Search UI Components?

Search UI Components are front end packages for JavaScript-powered frameworks including React. Search UI Components let you build customized search interfaces and result pages for your SearchStax Studio app.

Do I have to use Drupal with React?

React is not dependent on any specific CMS and can be used with a variety of different back ends, DXPs, or anything else that can deliver content over an API.

By Kevin Montgomery

Product Marketing Engineer

"...Content teams can still use CMS features such as drafts, authoring, and backups without relying on front end developers or pushing new code for content changes..."

You might also like: