Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 26, 2022 09:21 pm GMT

How to Create a Search Bar in React

What is a Search Bar?

A website search bar is a bar that allows users to search for content. The user clicks the search bar, types a query, and clicks "search," the magnifying glass icon.

For example a bar to search for blog posts:
Blog Search Bar

Let's create our search bar in React

You can see the demo at https://react-searchbar.vercel.app/

You can see the code on GitHub https://github.com/nicvazquez/react-searchbar

1) Create our React App

Let's create the React app with Vite using the following command:

npm create vite@latest

After this, it will ask us to complete with some options:

 Project name: ... react-searchbar Select a framework:  react Select a variant:  react

Excellent! Now run the following commands:

cd react-modalnpm installnpm run dev

If everything went well, you should have the application created, with the dependencies installed and have the project running on a local server, which in my case is http://127.0.0.1:5173/.
Vite running React app

2) Fetch API

We're going to fetch data from a rest API so we can use it when navigating our search bar.

This is not the point of the post, so we will not go into detail to fetch data from an API.

Put this code in your App.jsx. In this way, we will have a base of our application along with the data to be able to work with them.

import { useEffect, useState } from "react";import "./App.css";function App() {    const [users, setUsers] = useState([]);    const fetchData = async () => {        await fetch("https://jsonplaceholder.typicode.com/users")            .then((response) => response.json())            .then((data) => setUsers(data));    };    useEffect(() => {        fetchData();    }, []);    return (        <div>            {users?.map((user) => (                <p key={user.id}>{user.name}</p>            ))}        </div>    );}export default App;

Your app should look like this:

React App with Users from API

3) Create the search bar

Now let's get to the important stuff. Let's create the SearchBar component

  • In the src create a folder called components and inside it create another folder called searchbar.
  • Inside your searchbar folder create 2 files: SearchBar.jsx and searchbar.module.css.

Your project structure should look something like this:

Files and folders from the project

Great, now let's take our first steps in the SearchBar.jsx component

First, to have the base, we are going to create an input:

import React from "react";export const SearchBar = () => {    return <input placeholder="Search for an user" type="text" />;};

To see our changes, let's import the SearchBar component inside App.jsx

import { SearchBar } from "./components/searchbar/SearchBar";

The return of our App.jsx should look like this:

return (        <div>            <SearchBar />            {users?.map((user) => (                <p key={user.id}>{user.name}</p>            ))}        </div>    );

We already have the structure, but it still doesn't look good. Let's give it some padding

In our SearchBar.jsx file...

  • Import our CSS Modules file and add a className to the searchbar:
import React from "react";import styles from "./searchbar.module.css";export const SearchBar = () => {    return (        <input            className={styles.searchbar}            placeholder="Search for an user"            type="text"        />    );};
  • In searchbar.module.css let's add this code:
.searchbar {    padding: 0.5rem;}

So far our application should look like this:

React App

4) Add functionality to the search bar

Let's go back to our App.jsx.

For the search to work, we have to add a filter when we display the data on the screen.

  • Add this useState. We will use it later to store what the user typed
const [search, setSearch] = useState("")
  • To filter the data, we need to add the filter() JavaScript method in our JSX
{users    ?.filter((user) => user.name.toLowerCase().includes(search.toLowerCase()))    .map((user) => (    <p key={user.id}>{user.name}</p>))}
  • In our SearchBar.jsx we need to pass an onChange event to it via props. This will later serve to store what the user typed.
export const SearchBar = ({onChange}) => {    return (        <input            className={styles.searchbar}            placeholder="Search for an user"            type="text"            onChange={onChange}        />    );};
  • In App.jsx we send through props an anonymous function that stores the value of the input in the search state.
<SearchBar onChange={(e) => setSearch(e.target.value)} />

Now if we type into the search bar, the filtering will work correctly, since we are filtering based on what is stored in search.

Our App.jsx should look like this:

import { useEffect, useState } from "react";import "./App.css";import { SearchBar } from "./components/searchbar/SearchBar";function App() {    const [users, setUsers] = useState([]);    const [search, setSearch] = useState("");    const fetchData = async () => {        await fetch("https://jsonplaceholder.typicode.com/users")            .then((response) => response.json())            .then((data) => setUsers(data));    };    useEffect(() => {        fetchData();    }, []);    return (        <div>            <SearchBar onChange={(e) => setSearch(e.target.value)} />            {users                ?.filter((user) => user.name.toLowerCase().includes(search.toLowerCase()))                .map((user) => (                    <p key={user.id}>{user.name}</p>                ))}        </div>    );}export default App;

5) Done

That was it! If you have any questions or suggestions leave them in the comments.

You can see the demo at https://react-searchbar.vercel.app/

You can see the code on GitHub https://github.com/nicvazquez/react-searchbar

Thanks for getting here :)


Original Link: https://dev.to/nicvazquez/how-to-create-a-search-bar-in-react-5h0g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To