Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a search filter in ReactJS

Introduction

Hello there, programming enthusiast! Today, we're going to dive into the world of ReactJS and learn how to implement a search filter. Why do we need a search filter, you may ask? Imagine you have a website with tons of information, like an online store with thousands of products. You wouldn't want your users to scroll endlessly to find a specific item, would you? That's where the search filter comes into play. It's a handy tool that allows users to quickly find the information they need.

What is ReactJS?

Before we start, let's talk about ReactJS. ReactJS is a JavaScript library for building user interfaces. Think of it as the building blocks for creating the visual part of your website, like the navigation menu, buttons, and the actual content. ReactJS is popular because it's efficient, flexible, and it lets you create complex UIs with ease.

In this tutorial, we'll focus on a specific feature of ReactJS: the search filter. But don't worry if you're new to programming or ReactJS. We'll explain everything step by step with simple language and plenty of code examples.

Understanding the Search Filter

Think of a search filter as a magic box. You put something in (the search query), the box does some magic (the filtering process), and it gives you something back (the search results). The magic inside the box is what we call the algorithm, which is just a fancy way of saying "a step-by-step procedure for calculations."

In our case, the algorithm will look at the search query and compare it with the information we have. If it finds a match, it'll show it in the search results. If it doesn't, it'll show nothing or maybe a message saying "No results found."

Setting Up the ReactJS Project

First things first, we need to set up our ReactJS project. If you haven't installed ReactJS yet, you can do it by running the following command in your terminal:

npx create-react-app react-search-filter

This command will create a new ReactJS project called "react-search-filter". Feel free to change the name to whatever you like.

Once the command finishes running, navigate to your project's folder with:

cd react-search-filter

Creating the Search Component

In ReactJS, we build interfaces using components, which are like custom HTML elements. We're going to create a new component for our search filter. Let's call it "Search".

First, create a new file called "Search.js" in the "src" folder of your project. Then, write the following code in it:

import React from 'react';

class Search extends React.Component {
  render() {
    return (
      <div>
        <input type="text" placeholder="Search..." />
      </div>
    );
  }
}

export default Search;

This is a basic ReactJS component. All it does is render (show) an input field where users can type their search query. The "placeholder" attribute is just a text that appears in the input field before the user starts typing.

Adding the Search Logic

Now, let's make our search filter actually do something. We'll start by creating a list of data to search from. For simplicity, let's just use an array of strings. Add the following code to the top of your "Search" component:

class Search extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      query: '',
      data: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape']
    };
  }

  // rest of the code...
}

Here, we're introducing a new concept: the state. In ReactJS, the state is a built-in object that contains data that might change over time or when some event happens, like a user typing in an input field.

We're storing two things in our state: the search query and the data to search from. The search query is initially an empty string ('') because the user hasn't typed anything yet.

Next, let's add the actual search logic. We're going to use the JavaScript filter method, which creates a new array with all elements that pass a test (provided as a function). Add the following method to your "Search" component:

filterData() {
  const query = this.state.query.toLowerCase();

  return this.state.data.filter(element => element.toLowerCase().includes(query));
}

This method converts the search query and the data to lowercase and checks if the data includes the query. If it does, it adds it to the new array. If it doesn't, it ignores it.

Now, let's show the search results. Replace the render method with the following code:

render() {
  const filteredData = this.filterData();

  return (
    <div>
      <input type="text" placeholder="Search..." value={this.state.query} onChange={this.handleInputChange} />
      <ul>
        {filteredData.map(element => <li key={element}>{element}</li>)}
      </ul>
    </div>
  );
}

Here, we're calling the filterData method and storing the result in the filteredData variable. Then, we're displaying each element of the filtered data in a list (<ul> stands for "unordered list" and <li> stands for "list item").

The map method creates a new array by applying a function to every element of an array. In this case, the function takes an element of the filtered data and returns a list item with that element.

The key attribute helps ReactJS identify which items have changed, are added, or are removed, and it must be a unique value. We're just using the element itself as the key because we know it's unique in our data.

Notice that we're using the onChange attribute in the input field. This attribute accepts a function that will be called every time the user types or deletes something in the input field.

Now, you might be wondering: "What's this handleInputChange function? We didn't define that!" And you're right. Let's define it now. Add the following method to your "Search" component:

handleInputChange = event => {
  this.setState({ query: event.target.value });
};

This method updates the search query in the state every time the user types or deletes something in the input field. The event.target.value is just the current text in the input field.

And voila! You have your search filter in ReactJS. Try typing something in the input field and see how the list updates in real time. Isn't that cool?

Final Thoughts

Congratulations! You've just made a search filter in ReactJS. As you can see, ReactJS makes it easy to create dynamic and interactive interfaces.

Remember, practice makes perfect. Try creating a search filter with different data or adding more features, like sorting the results.

Happy coding!