Create a Simple Search Component in React.js using React Hooks (2024)

A simple tutorial on building a dynamic search component in React with the use of hooks

Shashank Singh

·

Follow

Published in

Geek Culture

·

8 min read

·

May 25, 2021

--

Create a Simple Search Component in React.js using React Hooks (3)

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

  1. Node.js installed on your system
  2. create-react-app package installed
  3. Preferably, an IDE
  4. 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-apppackage, 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:

  1. App.test
  2. App.css
  3. index.css
  4. logo.svg
  5. serviceWorker.js
  6. 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 SearchListcomponents. 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 toLowerCasefunction, 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 Searchcomponent.

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 Searchcomponent’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 SearchListcomponent 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.

Create a Simple Search Component in React.js using React Hooks (2024)

FAQs

How do I create a search component in react JS? ›

Create a React app called react search component by running the command npx create-react-app react-search-component, then install the axios package by running npm install axios or yarn add axios.

How do I create a search filter in react JS? ›

We accomplish the functionality in 4 steps:
  1. Access the search query value using “event. target. value“.
  2. Make a copy of list of items.
  3. Filter list to include items with search query.
  4. setState() to update the list with filtered values.

How do I create a dynamic search box in ReactJS? ›

We can create an array of all values or objects in ReactJS. After that, when a user searches for any value, we can use the filter() method to filter all objects from the array matching the search input value. We can use the match() method to check whether the input matches the current object property.

How to make search functionality in js? ›

Using JavaScript

In the HTML code of search bar, we gave the input an id=”searchbar” and onkeyup we called, the function “search_animal”. onkeyup calls the function every time a key is released on the keyboard. We first get our input using getElementById.

How do you implement live search in react? ›

React Js Custom Live or Instant Search Example
  1. Step 1: Create React Project.
  2. Step 2: Create Live Search Component.
  3. Step 3: Style Module with CSS.
  4. Step 4: Import Component in App Js.
  5. Step 5: Run + Test App.
Jun 29, 2023

How do I create a search box to filter data? ›

1. Use of Data Validation to Create Filtering Search Box for Excel Data
  1. Firstly, you need to select a cell that you want to use as a Filtering Search Box. ...
  2. Secondly, from the Data tab >> go to the Data Tools feature >> then choose the Data Validation command >> after that select the Data Validation option.

How to create custom filter method in JavaScript? ›

Let's go through step by step on how the filter() works.
  1. Create an empty array filterArr .
  2. Loop through the array elements.
  3. Called the filterFunc function with the current element as the argument.
  4. If the result is true, push the element to the filterArr array.
  5. Return filterArr array after going through all the elements.
Feb 21, 2019

How do I add a search to API? ›

Create a search interface with the Query API
  1. Build a search interface.
  2. Configure a search application.
  3. Generate OAuth credentials for the application.
  4. Query the index.
  5. Display query results. Handle supplemental results. Handle people results. Highlight snippets. ...
  6. Retrieve additional results.
  7. Sort results.
  8. Add filters.

How do I add a search box to a dropdown list in react JS? ›

  1. Add “react-select” npm package to package. json. ...
  2. Declare the dropdown options. ...
  3. Include <Select/> component in the JSX code. ...
  4. Bind React state with <Select/> dropdown value. ...
  5. JavaScript function to handle onChange events. ...
  6. Enable search functionality.

How do I add a search icon to my navbar in react? ›

This tutorial takes it forward from there.
  1. Step 1 - Show / Hide the Search Input. To show the search input, set the showSearch prop to true, as shown: ...
  2. Step 2 - Set the Search Input Caption. ...
  3. Step 3 - Set the Search Input Icon. ...
  4. Step 4 - Handle the Callback. ...
  5. Step 5 - Styling.
Nov 7, 2022

What is a dynamic search function? ›

What is a dynamic search? Dynamic searching is the functionality that allows a user to type into a search field to have the results filter and render instantly on the screen.

How do you add search functionality in HTML? ›

This uses a few HTML elements:
  1. <form> - This element is for user input.
  2. <input> - This element has many types the one we will use today is search.
  3. <button> - This element will submit the form and start the search.

How do I create a custom checkbox in React? ›

Customize CheckBox Appearance

Define own CSS rules according to your requirement and assign the class name to the cssClass property. The background and border color of the CheckBox is customized through custom classes to create primary, success, warning, danger, and info type of checkbox.

How do you create a search box in Aura component? ›

how to create a search box filter using Aura component
  1. use a Search Input With Spinner above on table,In that Search Input we need to type what ever want then press ENTER. ...
  2. Please clarify your specific problem or provide additional details to highlight exactly what you need.
Nov 29, 2022

How do I add a search box to a dropdown list in React js? ›

  1. Add “react-select” npm package to package. json. ...
  2. Declare the dropdown options. ...
  3. Include <Select/> component in the JSX code. ...
  4. Bind React state with <Select/> dropdown value. ...
  5. JavaScript function to handle onChange events. ...
  6. Enable search functionality.

How do I create a custom select component in React js? ›

How to create a Dropdown select component in React?
  1. Analyze the dropdown component.
  2. Create a dropdown input UI.
  3. Create a dropdown menu UI.
  4. Open/close dropdown menu handler.
  5. Handle select/deselect dropdown item.
  6. Create multiple dropdown select.
  7. Create a searchable dropdown select.
  8. Add onChange callback.

How do I create a React Web component? ›

How can you create a Web Component?
  1. Create a new class and extends HTMLElement.
  2. Use this class to create the component and its logic.
  3. Define the new element using the global function customElements.define()
Aug 21, 2019

References

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5888

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.