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
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;
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;
}
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"
}]
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
Your page should be looking like this now:
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;
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
Result
Your functional Search Bar will be looking like this:
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)
Very helpful article. Many thanks
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.
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
Ahh nice one, thank you π
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
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!
Nice post
thanks :)
Thanks it was a great help
What if no search results? How can we display a 'No results found' error?
We can check the length of the filteredData array. If it is less than 1 then no results.
sda