Categories
React Projects

Create a Search Filter App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a search filter app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app search-filter

with NPM to create our React project.

Create the Search Filter App

To create the search filter app, we write:

import { useState, useMemo } from "react";

const images = [
  {
    url: "https://images.dog.ceo/breeds/affenpinscher/n02110627_4597.jpg",
    description: "affenpinscher"
  },
  {
    url: "https://images.dog.ceo/breeds/akita/Akita_Inu_dog.jpg",
    description: "akita"
  },
  {
    url: "https://images.dog.ceo/breeds/retriever-golden/n02099601_7771.jpg",
    description: "golden retriever"
  }
];

export default function App() {
  const [keyword, setKeyword] = useState();
  const filteredImages = useMemo(() => {
    if (!keyword) {
      return images;
    }
    return images.filter(({ description }) => description.includes(keyword));
  }, [keyword]);

  return (
    <div className="App">
      <input value={keyword} onChange={(e) => setKeyword(e.target.value)} />
      <br />
      {filteredImages.map((fi) => {
        return (
          <div key={fi.description}>
            <img
              src={fi.url}
              alt={fi.description}
              style={{ width: 200, height: 200 }}
            />
            <p>{fi.description}</p>
          </div>
        );
      })}
    </div>
  );
}

We have the images array, which we want to search with the input box.

In the App component, we add the keyword state, which we create by th useState hook.

Then we use the useMemo hook to compute the filteredImages value.

We add a callback that checks for the keyword value.

If there’s no keyword value, then we return the images array.

Otherwise, we return the images array items that have the description that includes the keyword .

The 2nd argument has an array with the keyword variable since we want to updated filteredImages according to the keyword value.

filtereddImages is only updated with keyword changes.

Then in the return statement, we add the input box.

We set the onChange handler to set the keyword state.

Then we render the filteredImage items with the map method.

Conclusion

We can add a search filter easily with React’s useMemo hook and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *