How to integrate Search API in react?
» Prerequisite
-
Hey there, everyone! In the blog post, we will look at how we can integrate Algolia Instant Search API in React.
-
So, Let’s get into it!
-
First, Create your account at Algolia’s website
-
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.
- 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
- Open the terminal and install Algolia Search and React Instant Search by running the command.
npm install algoliasearch react-instantsearch
-
This will allow us to interact with Algolia’s search API.
-
After it is done, Open your react project in VS code.
-
And in the App.js file, let’s start by importing the algolia search from the ‘algoliasearch/lite’ package.
-
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.
-
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');
-
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.
-
These keys are needed to be kept secret.
» Create a .env file
-
So, what we will do is use dotenv file.
-
In the terminal run the command
npm i dotenv
-
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.
-
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
- 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);
-
Then in the search client variable pass the algoliaAppID variable and algoliaApiKey variable instead of the actual id and key.
-
And don’t forget to add .env into the .gitignore file. That’s important.
-
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.
-
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>
);
}
-
We also have a search box component with the className container which is used to center the component.
-
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.
» Import hits widget.
- 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';
- 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>
);
}
-
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.
-
This is the data that you’ve provided in your JSON file, and have added it as a record on Algolia.
-
And then in the function named app, we call the Hits with the hit component as a prop.
-
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.
» Highlight the Search result.
-
We can even highlight the matches.
-
Just like this:
- 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>
);
}
-
It takes two props:
-
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.
-
hit that represents the search result (or hit) for which you want to highlight the specified attribute.
-
You can highlight whatever attribute you want from the data you’ve provided to Algolia.
-
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.
- 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?
-
So how can we show other records present in our data? Simple Answer to this. We can Paginate our result.
-
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>
);
}
- Save the file and refresh the site and as you scroll there you have pagination.
- 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.
- 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>
);
}
- Let’s now search once again for iPhones and see it higlights and even shows 40 hits for it.
- 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!😊