Implementing a Search Bar in React.

Implementing a Search Bar in React.

Do you want to improve user experience by preventing your users from sifting through endless lines of text to find the data they’re looking for? Look no further! In this article, I’ll walk you through a step-by-step guide on how to create a search bar in React that will save your users time and frustration.

We’ll be creating a search bar that searches for names of people by filtering names from a JSON file. The data will be the test data obtained from a website called mockaroo.com

Prerequisite

  • Knowledge of vanilla javascript and its object methods.

  • Basic knowledge of React and its hooks.

Getting the test data from Mockaroo.

To get the test data that we’ll be using for this project we will first visit https://www.mockaroo.com/, here we can get the test data of the people which we’ll need to be used in the search bar. For this project, we will be using only the first_name field name. You will change the format of the data to JSON and then click on the generate data button. The gotten data should then be stored in a data.json file in our React app project.

Now we will be working on the structure of the search bar. We will create our search bar in our App.js file. We will do this by first creating a form field with a className of the search bar. Inside the form field, we will create an input field with a placeholder attribute of Search Name..., but you can name yours depending on what you’ll be using your search bar for. The search bar should have a button placed beside it. The text on the button should read Search. Just below the search bar, we will create a div with a className of results, this will be the text area in which the names we search for will be shown. We will also import our styles from ./App.css.
The jsx of our search bar should then look like this:

import "./App.css";

function App() {
  return (
    <div className="App">
      <div className="searchbar-container">
        <form className="searchbar">
          <input
            type="text"
            placeholder="Search Name..."
            onChange={handleFilter}
          />
          <button>Search</button>
        </form>
          <div className="results"></div>

      </div>
    </div>
  );
}

export default App;

The search bar with minimal styling in the App.css should then look like this:

.App {
  background-color: grey;
  margin: 0px;
  height: 100vh;
  display: flex;
  justify-content: center;
  padding-top: 200px;
}
.searchbar {
  display: flex;
  align-items: center;
}
input {
  height: 50px;
  width: 500px;
  border: 0px;
  font-size: 20px;
  border-radius: 25px 0 0 25px;
  padding-left: 20px;
  background-color: #201e1e;
  color: white;
}
input::placeholder {
  color: grey;
  opacity: 1;
  font-size: 20px;
}
button {
  height: 50px;
  width: 80px;
  border: 0px;
  color: white;
  background-color: blue;
  border-radius: 0 25px 25px 0;
  border: 1px solid white;
  font-size: 20px;
}
.results {
  background-color: #201e1e;
  color: white;
  height: 100px;
  width: 500px;
  overflow: hidden;
  overflow-y: auto;
  margin-left: 20px;
  font-size: 20px;
}
.results::-webkit-scrollbar {
  display: none;
}
.results-div {
  padding-left: 5px;
  height: 10px;
}

You can ignore the styles for the search results for now, but they will be used later on when we have completed our App.js file.

Mapping over our JSON data

Now that we’re done with the structure and styling of our search bar, we will import our JSON data from our previously created data.json file. To import this data we will have to import the data and save it into a variable name like so: import Data from "./data.json". Now to create the search results in the results div, we will then map over the Data we received from the data.json file. Inside the map, we will create an anonymous function that takes in two parameters a value parameter and a key parameter. This function will return a <p> tag that has a value of value.first_name since our JSON data has first_name keys.


import "./App.css";
import React from "react";
import Data from "./data.json";

function App() {

  return (
    <div className="App">
      <div className="searchbar-container">
        <form className="searchbar">
          <input
            type="text"
            placeholder="Search Name..."
            onChange={handleFilter}
          />
          <button>Search</button>
        </form>
        {results.length !== 0 && (
          <div className="results">
            {results.slice(0, 15).map((value, key) => {
              return <p className="results-div">{value.first_name}</p>;
            })}
          </div>
        )}
      </div>
    </div>
  );
}

export default App;

The search bar would need a state to monitor changes when its value changes. To do that we will be setting the initial value of the state to an empty array which is a falsy value. Using this will make it possible to detect typing of words since typed words are not a falsy value.


import "./App.scss";
import React from "react";
import Data from "./data.json";

function App() {
    const [results, setResults] = React.useState([]);

  return (
    <div className="App">
      <div className="searchbar-container">
        <form className="searchbar">
          <input
            type="text"
            placeholder="Search Name..."
            onChange={handleFilter}
          />
          <button>Search</button>
        </form>
        {results.length !== 0 && (
          <div className="results">
            {results.slice(0, 15).map((value, key) => {
              return <p className="results-div">{value.first_name}</p>;
            })}
          </div>
        )}
      </div>
    </div>
  );
}

export default App;

To manage the state of the search bar, we will need to create an event handler for the search bar. For this, we will create a function called handleFilter that takes in an event as a parameter. Inside the function we will create a variable called searchWord and give it a value of event.target.value this will make us be able to use the variable to compare with the MockData from our JSON data. We will also create a variable called newFilter and save it to MockData.filter and then create a function inside the filter method and give it a value parameter. This function will return a value.first_name and check if it has the searchWord using the includes operator. To make searching accurate we will first convert the data obtained from the JSON file and the form data to lowercase using the toLowerCase keyword. To make the results div disappear when the search input field is empty we will create an if/else statement that sets the state to an empty array which is a falsy value if we leave the search bar empty and sets the state of the search bar to the value of the newFilter variable if something is typed into the search bar.


import "./App.css";
import React from "react";
import Data from "./data.json";

function App() {
  const [results, setResults] = React.useState([]);

  const handleFilter = function (event) {
    const searchWord = event.target.value;
    const newFilter = Data.filter((value) => {
      return value.first_name.toLowerCase().includes(searchWord.toLowerCase());
    });
    if (searchWord === "") {
      setResults([]);
    } else {
      setResults(newFilter);
    }
  };
  return (
    <div className="App">
      <div className="searchbar-container">
        <form className="searchbar">
          <input
            type="text"
            placeholder="Search Name..."
            onChange={handleFilter}
          />
          <button>Search</button>
        </form>
        {results.length !== 0 && (
          <div className="results">
            {results.slice(0, 15).map((value, key) => {
              return <p className="results-div">{value.first_name}</p>;
            })}
          </div>
        )}
      </div>
    </div>
  );
}

export default App;

With all of this done, the basic structure and function of the search bar have been completed, but to make the search bar look more professional we will be adding a search bar clearing functionality.

Setting up clearing search bar functionality.

It is necessary to create a button that clears all we have written in our search bar input field because this saves users the stress of manually erasing what they have typed. So it makes using the search bar easier and more practical.

To clear the text the user inputs we will first of all have to create a state that will represent the text that is in the input field.

const [search, setSearch] = React.useState("");

We will call this state search and set its value to an empty string. To prevent the searchWord value in our handleFilter event handler function from having a different value from our search we will set our search value using setSearch to searchWord.


 const searchWord = event.target.value;
    setSearch(searchWord);

We will then create another button with a text of Clear on it. We will use a ternary operator to make this clear button conditionally rendered if the value of search.length is not equal to zero and the search button to be rendered if the condition is not met.


  {search.length !== 0 ? (
            <button>Clear</button>
          ) : (
            <button>Search</button>
          )}

To clear the text in the search bar input field we will create an onClick event handler function called clearSearch. Inside the clearSearch function, we will change the state of results to an empty array using setResults and also change the state of search to an empty string using setSearch.


const clearSearch = function () {
    setResults([]);
    setSearch("");
  };

We will then set the value of the button onClick attribute to be equal to clearSearch.

<button onClick={clearSearch}>Clear</button>

The code in our App.js file should then look like this:



import "./App.css";
import React from "react";
import Data from "./data.json";
function App() {
  const [results, setResults] = React.useState([]);
  const [search, setSearch] = React.useState("");

  const handleFilter = function (event) {
    const searchWord = event.target.value;
    setSearch(searchWord);
    const newFilter = Data.filter((value) => {
      return value.first_name.toLowerCase().includes(searchWord.toLowerCase());
    });
    if (searchWord === "") {
      setResults([]);
    } else {
      setResults(newFilter);
    }
  };
  const clearSearch = function () {
    setResults([]);
    setSearch("");
  };
  return (
    <div className="App">
      <div className="searchbar-container">
        <form className="searchbar">
          <input
            type="text"
            placeholder="Search Name..."
            onChange={handleFilter}
            value={search}
          />

          {search.length !== 0 ? (
            <button onClick={clearSearch}>Clear</button>
          ) : (
            <button>Search</button>
          )}
        </form>
        {results.length !== 0 && (
          <div className="results">
            {results.slice(0, 15).map((value, key) => {
              return <p className="results-div">{value.first_name}</p>;
            })}
          </div>
        )}
      </div>
    </div>
  );
}

export default App;

With this, the search bar can now be cleared easily by clicking on the clear button, instead of manually deleting each of the letters individually helping us to save time.

You can now modify your search bar to meet your design standards and decide where you’ll get your search bar data based on how you choose to apply the search bar in your project.

Here is what the final result should look like:

CONCLUSION

In conclusion, search bars have become a necessary element of modern web design, providing users with a convenient way to find the information they need quickly and easily. They help us to get the data we are looking for whether on a website, app, or platform.

Search bars can be used in different scenarios, and apart from their functionality, they are also visually appealing. The search bar created in this project is just a basic search bar, but search bars can be modified through the use of icons and styling to meet a variety of design standards. Understanding how search bars work and knowing how to modify them is a necessary skill for both frontend and backend developers.