How to Create a Search Bar in React
Tags: react, javascript, beginners, tutorial
Published: 2022-08-26 21:21:00

## 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.

Example:

![Blog Search Bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfg1n9czabcz0mfw27oi.png)
 
## 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-modal
npm install
npm 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w49308jgkakd1b3faw8l.png)

### 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.

```jsx
import { useEffect, useState } from "react";
import "./App.css";

function App() {
	const [users, setUsers] = useState([]);

	useEffect(() => {
		void fetch("https://jsonplaceholder.typicode.com/users")
			.then((response) => response.json())
			.then((data) => setUsers(data));
	}, []);

	return (
		<div>
				<ul>
					{users.map((user) => (
						<li key={user.id}>{user.name}</li>
					))}
				</ul>
			}
		</div>
	);
}

export default App;
```

Your app should look like this:

![React App with Users from API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvu6i300uuwbvyfyc2az.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47eetvsfihlui3f3p38d.png)
 
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:
```jsx
import React from "react";

export const SearchBar = () => {
	return <input placeholder="Search for an user" type="search" />;
};
```

To see our changes, let's import the SearchBar component inside `App.jsx`
```jsx
import { SearchBar } from "./components/searchbar/SearchBar";
```

The return of our `App.jsx` should look like this:
```jsx
return (
		<div>
			<SearchBar />
			<ul>
				{users.map((user) => (
					<li key={user.id}>{user.name}</li>
				))}
			</ul>
		</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:
```jsx
import React from "react";
import styles from "./searchbar.module.css";

export const SearchBar = () => {
	return (
		<input
			className={styles.searchbar}
			placeholder="Search for an user"
			type="search"
		/>
	);
};
```

- In `searchbar.module.css` let's add this code:
```css
.searchbar {
	padding: 0.5rem;
}
```
So far our application should look like this:

![React App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yzqy5706v947h442ogi.png)

### 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
```jsx
const [search, setSearch] = useState("")
```

- To filter the data, we need to add the `filter()` JavaScript method in our JSX
```jsx
const results = users.filter((user) =>
	user.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())
);
```

- Once we have the filtered data, we must iterate it. Also as a plus we will show a message if there are no users to show
````jsx
{
	<ul>
		{results.length === 0 ? (
			<p>There are no users to display</p>
		) : (
			results.map((user) => <li key={user.id}>{user.name}</li>)
		)}
	</ul>
}
```

- 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.
```jsx
export const SearchBar = ({onChange}) => {
	return (
		<input
			className={styles.searchbar}
			placeholder="Search for an user"
			type="search"
            onChange={onChange}
		/>
	);
};
```

- In `App.jsx` we send through props an anonymous function that stores the value of the input in the `search` state.
```jsx
<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:
```jsx
import { useEffect, useState } from "react";
import "./App.css";
import { SearchBar } from "./components/searchbar/SearchBar";

function App() {
	const [users, setUsers] = useState([]);
	const [search, setSearch] = useState("");

	useEffect(() => {
		void fetch("https://jsonplaceholder.typicode.com/users")
			.then((response) => response.json())
			.then((data) => setUsers(data));
	}, []);

	const results = users.filter((user) =>
		user.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())
	);

	return (
		<div>
			<SearchBar onChange={(e) => setSearch(e.target.value)} />
			{
				<ul>
					{results.length === 0 ? (
						<p>There are no users to display</p>
					) : (
						results.map((user) => <li key={user.id}>{user.name}</li>)
					)}
				</ul>
			}
		</div>
	);
}

export default App;
```

### 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 :)