25 Jan 2023

Implementing a search feature in a React application

Implementing a search feature in a React application can be a straightforward task, but it can also become quite complex depending on the requirements of the project. In this blog post, we will cover the basics of adding a search feature to a React application and explore some of the more advanced options available.

First, let's start by creating a simple search bar component. This component will take in a search term as input and pass it to a callback function, which will then be responsible for handling the search logic.

import React, { useState } from 'react';

const SearchBar = ({ onSearch }) => {
  const [searchTerm, setSearchTerm] = useState('');

  const handleSearch = (e) => {
    e.preventDefault();
    onSearch(searchTerm);
  };

  return (
    <form onSubmit={handleSearch}>
      <input
        type="text"
        value={searchTerm}
        onChange={e => setSearchTerm(e.target.value)}
        placeholder="Search..."
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default SearchBar;

In the above code, we have created a simple search bar component that takes in an onSearch callback prop. The component uses the useState hook to keep track of the current search term entered by the user. When the form is submitted, the handleSearch function is called, which in turn calls the onSearch callback prop and passes in the current search term.

Next, we will create a search results component that will display the results of the search. This component will take in an array of results as a prop and render them in a list.

import React from 'react';

const SearchResults = ({ results }) => {
  return (
    <ul>
      {results.map(result => (
        <li key={result.id}>{result.name}</li>
      ))}
    </ul>
  );
};

export default SearchResults;

In the above code, we have created a simple search results component that takes in an array of results as a prop. The component maps over the array of results and renders each result in a list item.

Now, we will use these two components in our main application to tie everything together. In this example, we will be searching for a list of users and displaying the results in the search results component.

import React, { useState } from 'react';
import SearchBar from './SearchBar';
import SearchResults from './SearchResults';

const users = [
  { id: 1, name: 'John Smith' },
  { id: 2, name: 'Jane Doe' },
  { id: 3, name: 'Bob Johnson' },
  // ...
];

const App = () => {
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = (searchTerm) => {
    const filteredResults = users.filter(user => user.name.toLowerCase().includes(searchTerm.toLowerCase()));
    setSearchResults(filteredResults);
  };

  return (
    <>
      <SearchBar onSearch={handleSearch} />
      <SearchResults results={searchResults} />
    </>
  );
};

export default App;

In the above code, we have imported our SearchBar and SearchResults components and created a list of users to search through. We then use the useState hook to keep track of the search results and pass the handleSearch function as a prop to the SearchBar component. This allows the SearchBar component to call the handleSearch function when the form is submitted and pass in the current search term. The handleSearch function then filters through the list of users and sets the filtered results to the searchResults state. The SearchResults component is then passed the searchResults state as a prop and renders the results in a list.

There are many ways to implement a search feature in a React application, and this is just one example. Other options include using a library such as lodash for more advanced filtering options or using a third-party API to fetch data and search through it. Additionally, it is possible to add pagination, sorting, and other features to the search results, but that would require more advanced code and this is just a basic example.

In conclusion, implementing a search feature in a React application can be relatively simple with a few basic components and some state management. With a little more complexity, however, it can become a powerful tool for searching through large sets of data.