Implementing a Search Box and Results Component

Discover what you can do with the SearchBox and Hits components and try them yourself in this lesson.

We'll cover the following

Overview

In the previous lesson, we talked about the root component of our search functionality and the composition of the search feature.

In this lesson, we will start implementing the building blocks of the search functionality by starting to import the SearchBox and the Hits component.

SearchBox

The SearchBox component is used to perform a text-based search query on Algolia by the user, which is the main entry point of any search functionality.

import React from 'react';
import {
  InstantSearch,
  SearchBox,
} from "react-instantsearch-dom";

class App extends React.Component {
	render() {
		return (
	        <div>
				<InstantSearch>
					<SearchBox/>
				</InstantSearch>
			</div>
		);
	}
}

SearchBox props

searchAsYouType: By default, searches follow an onChange event as it triggers search as you type. If searchAsYouType is set to false, searches are made after an onClick event or on pressing Enter.

onSubmit: It’s optional and takes a function as a prop that gets triggered on the submit event of the SearchBox.

onReset It’s optional and takes a function as a prop that gets triggered on the reset event of the SearchBox.

onClick: It’s optional and takes a function as a prop that gets triggered on the click event of the SearchBox or on pressing Enter.

translations: It’s optional and takes in option object:

  • submitTitle
  • resetTitle
  • placeholder

Hits

The Hits component is used to display the list of results and gets updated when a search query is triggered with filtered results returned from Algolia based on the searched text.

import React from 'react';
import {
	Hits,
  InstantSearch,
  SearchBox
} from "react-instantsearch-dom";

class App extends React.Component {
	render() {
		return (
			<div>
				<InstantSearch>
					<SearchBox/>
					 <Hits hitComponent={Hit} />
				</InstantSearch>
			</div>
		);
	}
}

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

Hits props

hitComponent takes in a function as a prop, which renders each hit from the result.

To see the above component in action, run the code below.

Get hands-on with 1400+ tech skills courses.