Search Bar in React JS!

Hi guys!

In this post we will be creating a fully functional search bar in React JS. Basically, we will have some dummy content, and we will use our search bar on it.

Check Out My hubpages

Note!. If you do not know how to create a react app, check out this video

Creating the Search Bar

Firstly, we will create the search bar which will be a basic text field. I will use Material UI for the input field. Material UI is an amazing React UI library that has many awesome components.

Install Material UI using the following command:

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:
Result

And you are done!

The code is on my github as well.
Link

Thank you all for reading this post!
Check out my recent Hubpages tutorial:

If you like my work, you can buy me a coffee and share your thoughts πŸŽ‰β˜•
Buy Me A Coffee

Until next time!
Cheers! πŸŽ‰

22