How to integrate Search API in react?

» Prerequisite

  1. Hey there, everyone! In the blog post, we will look at how we can integrate Algolia Instant Search API in React.

  2. So, Let’s get into it!

  3. First, Create your account at Algolia’s website

  4. It will take you to your account’s dashboard. There Create a new index and upload your records. Just like how I’ve shown in picture below.

Algolia’s Dashboard

  1. Next, Go to the settings tab and there you will have API keys, and application ID which we will need further.

» Install Algolia Search and React Instant

  1. Open the terminal and install Algolia Search and React Instant Search by running the command.
npm install algoliasearch react-instantsearch
  1. This will allow us to interact with Algolia’s search API.

  2. After it is done, Open your react project in VS code.

React App

  1. And in the App.js file, let’s start by importing the algolia search from the ‘algoliasearch/lite’ package.

  2. Then we will import the instant search and SearchBox from the ‘react-instantsearch’ package. These components are provided by Algolia for building search interfaces in React applications.

  3. We then import an external CSS file named ‘App.css’.

import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox } from 'react-instantsearch';
import './App.css';

const searchClient = algoliasearch('your-app-ID', 'your-API-key');
  1. Then we will also initialize a variable search client using the Algolia Search API and inside it, we provide or application ID and an admin API key.

  2. These keys are needed to be kept secret.

» Create a .env file

  1. So, what we will do is use dotenv file.

  2. In the terminal run the command

npm i dotenv 

  1. and you’ll have the dotenv package installed. After that’s done, create a dotenv file in the root directory and add your app ID and API key.

  2. Just like I’ve shown below. Add the React app at the start. It’s essential. because it is used to indicate that these variables are meant for React applications.

// .env file
REACT_APP_ALGOLIA_APP_ID = your-app-id
REACT_APP_API_KEY = your-api-key
  1. And then in the App.js file instead of using the API key and app ID in searchClient variable, what we will do is, create two const variables algoliaAppId and the algoliaApi key. And then we extract environment variables from the process.env object.
const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);
  1. Then in the search client variable pass the algoliaAppID variable and algoliaApiKey variable instead of the actual id and key.

  2. And don’t forget to add .env into the .gitignore file. That’s important.

  3. We can use API keys like this, but, it’s been suggested and is a best practice to Use a back-end proxy server when working with APIS. Store your API keys in the backend like node.js. Don’t use them from your front end.

  4. Then create and export the function App and in that, we return the Instant search component which takes searchClient and indexName as props provided by the Algolia react-instantsearch library. In indexName provide the value that you gave to your index.

import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox } from 'react-instantsearch';
import './App.css';

const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);

export default function App() {
  return (
    <InstantSearch searchClient={searchClient} indexName="content">
      <SearchBox className='container' />
    </InstantSearch>
  );
}
  1. We also have a search box component with the className container which is used to center the component.

  2. Now in the terminal run the command ‘npm start’ to start the server. And there you will have the search box. But there you will find no results yet, because we haven’t provided the hits or you can say search results. So let’s start with it.

React App

» Import hits widget.

  1. We have to use the hit widget to display the data. So, we have to first import it with SearchBox.
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch';
import './App.css';
  1. Then create a Hit function that is a custom React component that represents how each search result (or hit) should be displayed in the UI.
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch';
import './App.css';

const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);

function Hit({ hit }) {
  return (
    <>
      <div className='card'>
        <div>
          <img src={hit.image} alt={hit.name} />
        </div>
        <div className='content'>
          <h1>Name: <Highlight attribute="name" hit={hit} /></h1>
          <h3>Brand: {hit.brand}</h3>
          <p>Description: {hit.description}</p>
          <h4>Price: {hit.price}$</h4>
        </div>
      </div>
    </>
  );
}

export default function App() {
  return (
    <InstantSearch searchClient={searchClient} indexName="content">
      <SearchBox className='container' />
      <Hits hitComponent={Hit} />
    </InstantSearch>
  );
}
  1. It takes a hit as a prop, where the hit contains the data of a search result. Inside the Hit component, the data from the hit object is displayed, such as the item’s image, name, brand, description, and price.

  2. This is the data that you’ve provided in your JSON file, and have added it as a record on Algolia.

  3. And then in the function named app, we call the Hits with the hit component as a prop.

  4. Save the file and now you will see you have successfully displayed the records that you have provided to Algolia. now when we try searching for Phones it will display them. So that’s how we use hits to display the data.

Search Result

» Highlight the Search result.

  1. We can even highlight the matches.

  2. Just like this:

Search Result

  1. For it what we have to do is import the highlight widget with hits and then The Highlight component is used for displaying search results with highlighted matching terms.
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch';
import './App.css';

const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);

function Hit({ hit }) {
  return (
    <>
      <div className='card'>
        <div>
          <img src={hit.image} alt={hit.name} />
        </div>
        <div className='content'>
          <h1>Name: <Highlight attribute="name" hit={hit} /></h1>
          <h3>Brand: {hit.brand}</h3>
          <p>Description: {hit.description}</p>
          <h4>Price: {hit.price}$</h4>
        </div>
      </div>
    </>
  );
}

export default function App() {
  return (
    <InstantSearch searchClient={searchClient} indexName="content">
      <SearchBox className='container' />
      <Hits hitComponent={Hit} />
    </InstantSearch>
  );
}
  1. It takes two props:

  2. attribute that specifies the name of the attribute in the hit object that should be highlighted. In this case, attribute=“name” indicates that the “name” attribute of the hit object should be highlighted.

  3. hit that represents the search result (or hit) for which you want to highlight the specified attribute.

  4. You can highlight whatever attribute you want from the data you’ve provided to Algolia.

  5. Once done, save the file. and refresh the site now when we type something in the search bar, you will notice the search result gets highlighted.

» Paginating the hits.

  1. Now let’s suppose you have a huge data but as you can see here when you scroll down it just shows 20 records right?

Search Result

  1. So how can we show other records present in our data? Simple Answer to this. We can Paginate our result.

  2. First, we have to import the Pagination widget and then call the Pagination component in our App function. Like this:

import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits, Highlight, Pagination } from 'react-instantsearch';
import './App.css';

const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);

function Hit({ hit }) {
  return (
    <>
      <div className='card'>
        <div>
          <img src={hit.image} alt={hit.name} />
        </div>
        <div className='content'>
          <h1>Name: <Highlight attribute="name" hit={hit} /></h1>
          <h3>Brand: {hit.brand}</h3>
          <p>Description: {hit.description}</p>
          <h4>Price: {hit.price}$</h4>
        </div>
      </div>
    </>
  );
}

export default function App() {
  return (
    <InstantSearch searchClient={searchClient} indexName="content">
      <SearchBox className='container' />
      <Hits hitComponent={Hit} />
      <Pagination className='pagination-list' /> 
      // className='pagination-list' to style the pagination
    </InstantSearch>
  );
}
  1. Save the file and refresh the site and as you scroll there you have pagination.

Search Result

  1. I’ve applied CSS to it so that it can look better.
.pagination-list {
  list-style: none;
  padding: 0;
  text-align: center;
}

.pagination-list li {
  display: inline-block;
  margin: 0 5px;
  line-height: 30px;
  width: 30px;
  height: 30px;
  border: 1px solid #ccc;
  border-radius: 50%;
}

» Configure Widget.

  1. By default, Algolia just lists 20 hits. But you can increase that too with the help of the Configure widget. Just import it and in the App function call the configure component which will take hits per page as a prop. Set it to whatever number you want.
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits, 
Highlight, Pagination, Configure } from 'react-instantsearch';
import './App.css';

const algoliaAppId = process.env.REACT_APP_ALGOLIA_APP_ID;
const algoliaApiKey = process.env.REACT_APP_API_KEY;

const searchClient = algoliasearch(algoliaAppId, algoliaApiKey);

function Hit({ hit }) {
  return (
    <>
      <div className='card'>
        <div>
          <img src={hit.image} alt={hit.name} />
        </div>
        <div className='content'>
          <h1>Name: <Highlight attribute="name" hit={hit} /></h1>
          <h3>Brand: {hit.brand}</h3>
          <p>Description: {hit.description}</p>
          <h4>Price: {hit.price}$</h4>
        </div>
      </div>
    </>

  );
}

export default function App() {
  return (
    <InstantSearch searchClient={searchClient} indexName="content">
      <Configure hitsPerPage={40} />
      <SearchBox className='container' />
      <Hits hitComponent={Hit} />
      <Pagination className='pagination-list' />
    </InstantSearch>
  );
}
  1. Let’s now search once again for iPhones and see it higlights and even shows 40 hits for it.

Search Result

  1. You can also refer to Algolia’s documentation for this.

And That’s it! You’ve successfully learned How to integrate Algolia’s React Instant Search in the React App.

Thank You for reading and Happy coding!😊