Implementing a Highlight Component

Explore how search results can be improved by adding the Highlight component.

Overview

In the previous lesson, we added some functionality to our search component by adding the SearchBox and the Hits component that allows us to make a query request to the Algolia server and display results from this query.

In this lesson, we will learn how to improve the user search experience by adding a highlight feature that can show a user the highlighted attribute based on the searched query.

The Highlight component

In order to highlight matching keywords from the results based on a search query, we need to modify our Hits component to wrap the highlight around the specific attribute that we want the user to see.

import { Highlight } from "react-instantsearch-dom";
import React from "react";

const Hit = (props) => {
  return (
    <div>
      <img
        alt={props.hit.name}
        src={require(`../${props.hit.image}`).default}
      />
      <div className="title">
        <Highlight attribute="name" hit={props.hit} />
      </div>
      <div className="price">£{props.hit.price}</div>
    </div>
  );
};

export default Hit;

As you can see from the above snippet, we have imported the Highlight component and set name attribute as the value that is going to be highlighted based on the searched query.

Highlight props

  • attribute expects a type of string value that is required. The attribute value is what you want to highlight from the record (for example name attribute as per the above example).

  • hit expects a type object that is required. The value of this object is hit prop that is given from the hits component

  • tagName expects a type string that is optional. The value of this attribute is the HTML tag that you would like to use for the highlighted part of the string.

  • nonHighlightedTagName expects a type string which is optional. As the attribute name suggests, the value of this attribute is the HTML tag that you would like to use for the non highlighted part of the string.

Get hands-on with 1400+ tech skills courses.