DEV Community

Cover image for Search Bar in React JS!
Saleh Mubashar
Saleh Mubashar

Posted on • Edited on • Originally published at salehmubashar.com

Search Bar in React JS!

Hi guys!

In this post, we will learn how to create a fully functional search bar in React JS. We will start by setting up some sample content and then proceed to implement the search feature using the created search bar.

Read this post on my blog!


Creating the Search Bar

To create the search bar, we will start by creating a basic text field. For this tutorial, we will use Material UI, an excellent React UI library that provides various components. Follow these steps to install Material UI using npm:



npm install @mui/material


Enter fullscreen mode Exit fullscreen mode

In your app.js, import the text field component from Material UI. We will use the outlined variant of the text field.



import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List"
import "./App.css";

function App() {
  return (
    <div className="main">
      <h1>React Search</h1>
      <div className="search">
        <TextField
          id="outlined-basic"
          variant="outlined"
          fullWidth
          label="Search"
        />
      </div>
      <List />
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

You may notice a few things here. We are importing a file called List.js which we will create now. This will contain our list of dummy data.

Next, add the following CSS to your App.css:



.main {
    display: flex;
    height: 100vh;
    width: 100%;
    align-items: center;
    flex-direction: column;
    row-gap: 20px;
}

h1 {
    margin: 10px;
    font-size: 40px;
    color: rgb(1, 1, 59);
}

.search {
    width: 30%;
}

ul li {
    font-size: 20px;
} 


Enter fullscreen mode Exit fullscreen mode

Creating the dummy content

Create a new folder in your src folder called Components. Within this, create two files, a JSON file called ListData.JSON and the List.JS file.

For the sample text or content, I used Mockaroo. You can get all sorts of realistic test data from here. For this example, you can use my ListData.JSON too:



[{
    "id": 1,
    "text": "Devpulse"
}, {
    "id": 2,
    "text": "Linklinks"
}, {
    "id": 3,
    "text": "Centizu"
}, {
    "id": 4,
    "text": "Dynabox"
}, {
    "id": 5,
    "text": "Avaveo"
}, {
    "id": 6,
    "text": "Demivee"
}, {
    "id": 7,
    "text": "Jayo"
}, {
    "id": 8,
    "text": "Blognation"
}, {
    "id": 9,
    "text": "Podcat"
}, {
    "id": 10,
    "text": "Layo"
}] 


Enter fullscreen mode Exit fullscreen mode

Creating the List

Now we will map this data in the form of a List. Inside the List.JS file, add the following code:



import { React, useState } from 'react'
import data from "./ListData.json"

function List(props) {
    return (
        <ul>
            {data.map((item) => (
                <li key={item.id}>{item.text}</li>
            ))}
        </ul>
    )
}

export default List


Enter fullscreen mode Exit fullscreen mode

Your page should be looking like this now:

Browser View

Getting User Input

Now we need to store the user input in a state. We will do this using the onChange even handler on the text field and a function that updates a state every time the user types something.

Note: Always convert the input text to lower case when creating a search bar.

We will also pass down the state to the List component in the form of props.
Your App.js will look like this now:



import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List";
import "./App.css";

function App() {
const [inputText, setInputText] = useState("");
let inputHandler = (e) => {
//convert input text to lower case
var lowerCase = e.target.value.toLowerCase();
setInputText(lowerCase);
};

return (
<div className="main">
<h1>React Search</h1>
<div className="search">
<TextField
id="outlined-basic"
onChange={inputHandler}
variant="outlined"
fullWidth
label="Search"
/>
</div>
<List input={inputText} />
</div>
);
}

export default App;

Enter fullscreen mode Exit fullscreen mode




Filtering the Data

Now we will filter the data using the filter function and creating a new array called filteredData. We will map this array in place of the original.
We will convert the list data to lower case as well to match the user input. The user input can be accessed using props.
This will be your List.js:



import { React, useState } from 'react'
import data from "./ListData.json"

function List(props) {
//create a new array by filtering the original array
const filteredData = data.filter((el) => {
//if no input the return the original
if (props.input === '') {
return el;
}
//return the item which contains the user input
else {
return el.text.toLowerCase().includes(props.input)
}
})
return (
<ul>
{filteredData.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
)
}

export default List

Enter fullscreen mode Exit fullscreen mode




Result

Your functional Search Bar will be looking like this:
Result

And you are done!

The code is on my github as well.
Link


Thank you all for reading this post!
Check out my blog too!

Top comments (12)

Collapse
 
wayungi profile image
wayungi

Very helpful article. Many thanks

Collapse
 
ayobami profile image
David

Thank you for this information. πŸ‘.
But would the List component be able to import data from ListData.JSON file because you did not export data from the json file.

Collapse
 
salehmubashar profile image
Saleh Mubashar • Edited

Yes it would
since it is JSON data, you can simply import it as 'data'
you can think of the data file as simply an array

Collapse
 
ayobami profile image
David

Ahh nice one, thank you πŸ™

Collapse
 
astrobotme profile image
Aditya

This is Nice But When your search query exceeds one word or more .. it fails badly. Here Because the List items are single word and a single word query makes sense but in real-world applications where the things you were searching in will be more than one words so does your query
One Should use a better approach to handle it

Collapse
 
salehmubashar profile image
Saleh Mubashar

That's a great point. I completely overlooked that while writing this. Often times, real time searches work perfectly using only a few letters. But yeah, a better approach for real world applications does make more sense. Thanks for the comment!

Collapse
 
thejsdev profile image
the JS DEV

Nice post

Collapse
 
salehmubashar profile image
Saleh Mubashar

thanks :)

Collapse
 
sameervanjari profile image
Serious Sam

Thanks it was a great help

Collapse
 
crsandeep24 profile image
Sandeep Reddy

What if no search results? How can we display a 'No results found' error?

Collapse
 
salehmubashar profile image
Saleh Mubashar

We can check the length of the filteredData array. If it is less than 1 then no results.

if (filteredData.length < 1) {
   // something
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
prashant2372004 profile image
prashant2372004

sda