Creating a simple search field with react hooks: as a function component.

Subscribe to my newsletter and never miss my upcoming articles

I was trying to create a simple search function a few days ago and I didn't want to employ the use of any search service like; algolia or elastic. I found my way around it and I would have to admit that this would be my go-to solution for any simple search related stuff on the client-side(React).


Let's get started:

  • Create a project and Install react using the following command:

npx create-react-app my-app or npx create-react-app . and npm install axios -S

  • Now, in the src folder.

Add the following code to the App.js file:

import React, { useState, useEffect } from "react";
import axios from "axios";

export default function Users() {
  const [users, setUsers] = useState([]);
  const [search, setSearch] = useState("");
  const [filterUsers, setFilteredUsers] = useState([]);

  const fetchUsers = async () => {
    const res = await axios.get("https://jsonplaceholder.typicode.com/users");
    setUsers(res.data);
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  useEffect(() => {
    setFilteredUsers(
      users.filter(user =>
        user.name.toLowerCase().includes(search.toLowerCase())
      )
    );
  }, [search, users]);

  return (
    <div className="App">
      <div>
        <input
          type="text"
          placeholder="Search..."
          onChange={e => setSearch(e.target.value)}
        />
      </div>
      {filterUsers.map(item => (
        <div key={item.id}>
          <ul>
            <li>{item.name}</li>
          </ul>
        </div>
      ))}
    </div>
  );
}

Note:

  • react and two of the basic react hooks are imported: useState and useEffect.
  • hooks allows you to use some react features without writing a class component.
  • For the states: especially if you have ever used class components; [users, setUsers] = useState([]) => is similar to this.state.users and this.setstate
  • so, all the state variables are declared and an async/await function is created to get the API data, then the function is called in a useEffect hook.
  • another useEffect hook is called again to set the filtered users with the required fields that which are; name and search. search and users are passed as arguments in the useEffect hook to basically re-render if the state changes.
  • KeyNote: the useEffect react hook is like the combination of render, componentDidMount andcomponentDidUpdate.
  • Finally, in the return element, an input search box is created and the filterUsers state is mapped as an array to get the item properties.

The End.

Thanks for reading!


See the full code in action on codesandbox: codesandbox.io/s/react-search-function-qc0e..

No Comments Yet