Alt Text

Welcome to part-12 of the series. We will start to add the Search functionality in our blog. There are some gatsby plugin to add the search functionality, but we can add it with plain old react code.

I found this very good blog by Monica Powell to do it with react code.

Let’s first add the Search Bar by updating the index.js file as below. We are adding an input box to capture the user’s input.

index.jsindex.js

We are using useState hooks and set the default state with query as empty string and filteredData s empty array. You can read more about react hooks in my earlier post here.

Default stateDefault state

Next, we will do the handleInputChange function. Here, we are capturing the user input in event.target.value. We also have access to all posts in response.allMdx.edges. After that we are using filter to filter through all the posts which either matches the description, title or tags. Since, tags is an array of strings we are using join. After, that we are using setState to reset the query and filteredData and this will re-render the component.

handleInputChangehandleInputChange

Next, we are renaming the posts to allPosts. We are doing this so that we can make the value of posts conditional, based on whether the user have entered something in the search bar or need to see all posts.

allPostsallPosts

Next, we are updating the rendering logic to decide whether to show filteredData or allPosts.

hasSearchResultshasSearchResults

I did a mistake as we don’t have any description in our code but excerpt. So, updating the same and also adding author to the filtering logic.

mistakemistake

Let’s also add some styles in home.module.css for our search bar.

StylesStyles

This will show our Search bar as below in our project.

Search BarSearch Bar

And our Search Bar is fully working now.

Fully workingFully working

This completes part-12 of the series.

You can find the code for the same in this github repo.

This post is also available on DEV.