A simple tutorial on building a dynamic search component in React with the use of hooks
Shashank Singh · Follow
Published in · 8 min read · May 25, 2021
--
One of the most important components in any website is it’s Search Component, it instantly makes the user experience better and if made with a bit of care, it turns the website into a good designing masterpiece as well.
In this article, I’ll be making a Search react component which you can easily integrate in your own React web app. The search component even if seems a bit tricky sometimes is a fairly simple component especially if you know a bit of React.
When I first wanted to make my own Search component, I had to look in a lot of articles which were way too complicated and unnecessarily complicated a simple component.
So, I’ll be taking you through these few simple steps of making a search component on your own in React and will also be providing a Github repo for the same at the end.
Pre-requisites
Node.js
installed on your systemcreate-react-app
package installed- Preferably, an IDE
- Will to work on a Search component
Creating a React App
Firstly, we’ll create a React App with the help of the create-react-app
package, so we run the following commands:
npx create-react-app react-search
cd react-search
After this, we’d also want tachyons
(use of tachyons
is not necessary though if you don’t want to style the component here), so we add it using yarn with following commands:
yarn add tachyons
Now, you’re ready to start working on your React App.
Clearing the Clutter and Setting up App (optional)
So, now that you have created your app, open your working folder in your IDE and you see a lot of files are already there, but for the scope of this project (and usually all small-scale projects), we can remove a lot of these files and make your folder look a bit better. So, remove these files in your project’s src
folder:
App.test
App.css
index.css
logo.svg
serviceWorker.js
setupTests.js
This will clear up your src
folder where all of your work is going to be done.
Now, open your public
folder and go to index.html
, in the file, change the title
of your App to React Search (or anything that you like), i.e., replace <title>React App</title>
with <title>React Search</title>
and add the following line above it to use tachyons
in your app:
<link rel="stylesheet" href="https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css"/><title>React Search</title>
The version of the tachyons
might change in the above link, you can copy the newest command from here.
Now, open your App.js
and index.js
files in the src
folder and remove the unnecessary lines, after which they shall look like this (React.StrictMode
is optional though):
But do note that this is an optional step and you can leave whole of this step if you are not trying to create an app from scratch.
Creating Data File
There are two ways to go about here and it totally depends on you how you want your app to work.
The first one is to add the data with the useState
hook in the App.js
file itself. This may be a good way to go if we create a form for getting the data from the user (otherwise there will be too much clutter inside App.js
), but for the sake of simplicity of this article, we’ll be opting for the other way.
The second way is to create a different file and then import it inside the App.js
file and hence getting a clean look.
So, we start with creating a data
folder inside the src
folder, in this folder we create a file named initialDetails.js
. Now, this file will contain a list, which in turn contains details.
We use 5 main details, id, imgPath, name, email, address
for a person. For the images, I used the 8-bit avatar illustrations from Limitless Designs, you can also get it from here for free (may have to sign up). Then, I created a folder named img
inside the assets
folder in the public
folder and pasted five random pictures in the img
folder, naming them 1–5 with their given format.
The imgPath
variable for any given person would be a relative address from the public
folder (we’ll see later how to use this imgPath as React doesn’t allow for use of any items outside the src
folder).
Since it is a menial task to create data here, I’d ask you to just copy paste the code given below in your files and make the necessary changes if required.
After completing this part, we can finally move on to creating the actual app in React.
Now, we finally are ready to work, so what we’ll do first is create a new folder named components
in the src
folder. Here, we’ll create 4 new files, namely:
1. Card.js // Card component to display details
2. SearchList.js // Component to list out the cards
3. Scroll.js // Component for making the list scrollable
4. Search.js // Main search component
Card.js
We’ll start with the Card
component which will simply put the details of a person in a card component to make it look better.
The card component will receive a single person’s details and then displays them.
Here, in the line 7, we have used tachyons
for making a card and again in line 8 to make the image turn into an circle avatar. Next, we use the process.env.PUBLIC_URL
to access all the files in the public
folder and then concatenate the imgPath
variable to it for accessing the person’s image. After that, we simply display the details of a person.
SearchList.js
Next up, we look at the SearchList
component which as the name suggests, puts up these Card
components with the help of map
function.
First, we import the Card
component, then we use the map
function on filtered list obtained from the parent component in the render section. Through this map function, we render a different Card for each person by passing on the parameters required.
After this, in the return section we call the filtered
object which was created earlier.
Scroll.js
Now, if the SearchList
component were used as such, it would be acquiring up space on the whole of the screen as the data increases, to oppose that, a Scroll
component was created which is also fairly simple and self-explanatory.
In this component, the components inside it are rendered with a height of 70 viewport height
and turns them into a scrollable component for the y-axis if they overflow.
Search.js
Finally, we reach the Search
component, this is the most important component from the perspective of the article. Firstly, we import useState
from react
. Then, we import the Scroll
and SearchList
components. Next, in the Search
function, we use the useState
hook to initialise the value of the searchField state
with useState("")
(an empty string). After this, we use the filter
function on the details
list received from the parent.
In this filter function, we check for two values, the person’s name and their email and then convert them to lowercase with the toLowerCase
function, after which we use the includes
function to check if the search bar includes any of the letters in the details. If it does include the specified query, the specific person’s details are sent into filteredPersons
.
After this, we go to the return and create a heading for the component and an input box for searching details. All of these are stylised with the help of tachyons
package easily. In the input we put the value of onChange
attribute as the handleChange
function.
handleChange
function in turn sets the value of searchField
with setSearchField()
.
Now, for rendering all the details, a bit similar to what we did in SearchList
component, we create a function (look at the position, functions are to be created outside the return). This function wraps up the SearchList
component inside the Scroll
component and inside we pass the filteredPersons
object. Later, this function is called inside the return to render the results of the search query.
This completes our Search
component, and hence the main part of the article. Next, we move on to App.js
for completing this Search
component.
App.js
We edited this component earlier and made it look clean. Since we have created different components for our Search
functionality, we’ll have much less clutter inside App.js
while integrating it.
A clean App.js usually means a well created web app.
Firstly, we import the Search
component from the Search.js
file, then we import the initialDetails
list from the initialDetails.js file.
Then, we use tachyons
to stylise the web app and the Search
component’s details parameter is filled with the initialDetails
that was imported earlier.
With this, we complete our journey of creating a Search Component.
Lastly, we run our web app in our bash/command prompt with the following commands:
yarn start
Voila, now you have our own web app with a working search component.
If you followed the article until now, you’d have created a search box similar to the one shown below, you’re obviously welcome to make it better design wise as I mainly focused only on the structuring, organising and working part in the article, but a simple Search component should look like this.
Not always would you want all your search results showing up in your website, so for hiding it unless something is typed inside it, we simply do three small things, create a new state searchShow
with useState
and pass false
as the initial value to it (in my dummy project, I have set useState(true)
recently, as I want all my results to be available at first).
const [searchShow, setSearchShow] = useState(false);
Then, we check whether the input from the search bar is empty with the help of e.target.value
, in which case we set this searchShow
state to false
, otherwise we set it to true
with the help of setSearchShow
inside the handleChange
function.
if(e.target.value===""){
setSearchShow(false);
}
else {
setSearchShow(true);
}
After this, we add an if
statement to the searchList
function which checks whether searchShow
is true , and if true, it renders the SearchList and Scroll
components, otherwise it doesn’t.
if (searchShow) {};
Take a look at the new Search.js
file given below, the three changes that I talked above are made in lines 10, 29–34 and 38 (and 44 too).
Adding these five lines would effectively hide your SearchList
component and your web app shall look like this after changing.
Looks cool, doesn’t it? Give it a try yourself and if you face any problems feel free to contact me or look at my Github Repo or you can also look at this demo website hosted on Netlify.