How to Create a React Search Bar for Your Website
A search bar is an essential component of any website, allowing visitors to find the information they need quickly. If you are building a website using React, you can easily create a search bar to improve the user experience. In this article, we will guide you through the process of creating a React search bar step-by-step. By the end of this guide, you will have a fully functional search bar that can be integrated into your website.
Prerequisites for the Search Bar
Before we start, you should have a basic understanding of React and JavaScript. You will need to have Node.js and npm installed on your computer. You can download them from the official Node.js website if you don’t have them installed.
If you are looking for the code, You can find the code for this project on GitHub.
Setting up the React Project
To create a React search bar, you will need to create a new React project. You can do this by running the following commands in your terminal:
npx create-react-app search-app
cd search-app
npm start
This will create a new React project called search-app
. Once the project is created, you can open it in your browser by navigating to http://localhost:3000
.
Also Read: Next JS vs React: Which One Should You Choose?
Creating the Search Bar Component
The next step is to create the search bar component. In your project directory, under src
folder create a new file called SearchBar.js
where we will add the search bar component.
// ./src/SearchBar.js
import React from 'react';
const SearchBar = () => {
return (
<form>
<input type="text" placeholder="Search..." />
<button type="submit">Search</button>
</form>
);
}
export default SearchBar;
In the above code, we have defined a functional component called SearchBar
. The component returns a form with an input field and a submit button. We have also added a placeholder text to the input field.
Also Read – How to Fix It React Hook useEffect Has a Missing Dependency
Adding Styles in the Search Bar
To make the search bar look more appealing, we can add some styles to it. Create a new file called SearchBar.css
in your project directory and add the following code:
// ./src/SearchBar.css
form {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 1rem;
width: 100%;
}
input[type="text"] {
padding: 0.5rem;
border-radius: 0.25rem;
border: none;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
border: 1px solid rgba(0, 0, 0, 0.2);
width: 100%;
max-width: 250px;
margin-right: 0.5rem;
}
button[type="submit"] {
padding: 0.5rem;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 0.25rem;
cursor: pointer;
}
In the above code, we have defined some basic styles for the search bar. We have used flexbox to align the input field and the submit button. We have also added some padding and border-radius to the input field to make it look more appealing. The submit button has a blue background color and white text.
Also Read: Top 5 Free APIs for Your Next Project
Adding Functionality to the Search Bar
Now that we have created and styled the search bar, we need to add some functionality to it. We will use React hooks to add functionality to the search bar component.
import React, { useState } from 'react';
const SearchBar = () => {
const [searchQuery, setSearchQuery] = useState('');
const handleSearchInputChange = (event) => {
setSearchQuery(event.target.value);
}
const handleSearchSubmit = (event) => {
event.preventDefault();
console.log(`Searching for: ${searchQuery}`);
// Add your search functionality here
}
return (
<form onSubmit={handleSearchSubmit}>
<input
type="text"
placeholder="Search..."
value={searchQuery}
onChange={handleSearchInputChange}
/>
<button type="submit">Search</button>
</form>
);
}
export default SearchBar;
In the above code, we have added two new functions to the component: handleSearchInputChange
and handleSearchSubmit
. The handleSearchInputChange
function updates the search query state whenever the user types something in the input field. The handleSearchSubmit
function is called when the user clicks the search button or presses Enter.
When the form is submitted, the handleSearchSubmit
function logs the search query to the console. You can add your own search functionality here, such as making an API call to fetch search results and display them on the page.
Also Read: Top 5 Websites for Free and Beautiful Stock Images
Search Functionality Logic
To check our search functionality we are going to use some Pokemon Data. Initially, we will render all the data initially, but when we click on the search button the filtered data will be rendered. For that, we will import the data in App.js
file.
// ./src/App.js
import React, { useState } from "react";
import SearchBar from "./SearchBar";
import { pokedata as data } from "./data";
import "./App.css";
const App = () => {
const [filteredData, setFilteredData] = useState(data);
return (
<div className="container">
<SearchBar
data={data}
setFilteredData={setFilteredData}
/>
<div className="pokedex">
{filteredData.map((pokemon) => (
<div className="pokemon" key={pokemon.id}>
<div>{pokemon.name}</div>
<div>{pokemon.type}</div>
</div>
))}
</div>
</div>
);
};
export default App;
Here we have that SearchBar component that takes in two props: data
and setFilteredData
. The data prop is an array of objects that we want to filter through. The setFilteredData
prop is a function that we can call to update the filteredData
state in our App component. We can then use the filteredData
state to render the filtered data in our App component.
We have also mapped over the filteredData
state in our App component to render the filtered data. Also, We are using the id property of each object in the array as the key for each rendered element.
The styles for the mapped components are here –
// ./src/App.css
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
}
.pokedex {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
}
.pokemon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 1rem;
border: 1px solid black;
border-radius: 1rem;
width: 8rem;
height: 8rem;
}
Here is the function for the handleSearchSubmit
with the search logic. The value of the input field is set to the searchQuery
state variable. This will allow the user to see what they are typing in the input field.
const handleSearchSubmit = (event) => {
event.preventDefault();
console.log(`Searching for: ${searchQuery}`);
const filteredData = data.filter((pokemon) => {
return pokemon.name.toLowerCase().includes(searchQuery.toLowerCase());
});
setFilteredData(filteredData);
};
The code for this project is on GitHub
Conclusion
Creating a search bar in React is a simple and straightforward process. You can create a fully functional search bar with the following steps and add it to your website’s navbar. Remember to use React hooks to add functionality to your search bar component, and to style your search bar to make it look more appealing. Happy coding!
You may also like
How to add Google Web Stories in Next JS
Dec 14, 2023
·10 Min Read
In the fast-paced digital world, user engagement is key to the success of any website. One effective way to captivate your audience is by incorporating Google Web Stories into your Next JS website. These visually appealing and interactive stories can make your content more engaging and shareable. In this comprehensive guide, we’ll walk you through […]
Read More
How to send Emails in Next JS for Free using Resend
Nov 10, 2023
·7 Min Read
Sending emails in web applications is a crucial feature, and in this article, we will explore how to send Emails in Next JS for free using Resend. Next JS is a popular framework for building React applications, and Resend is a handy tool for email integration. By the end of this guide, you’ll have the […]
Read More
How to add Google Login in Next.js with Appwrite
Nov 01, 2023
·7 Min Read
Are you looking to enhance user authentication in your Next.js application? Integrating Social Login with Appwrite can be a game-changer. Add Google Login to your Next.js app with Appwrite. This article will guide you through the process, and practical tips to add Google Login in Next.js with Appwrite. GitHub Code: Google Login in Next.js with […]
Read More
JavaScript Project Ideas to Boost Your Portfolio
Oct 13, 2023
·3 Min Read
JavaScript is the backbone of web development, and mastering it is essential for any aspiring developer. While learning the basics is crucial, building real-world projects is the key to solidifying your knowledge. In this comprehensive guide, we’ll present a diverse range of JavaScript project ideas that cater to different skill levels and interests. These projects […]
Read More
How to Generate robots.txt in Next JS?
Oct 05, 2023
·4 Min Read
In the world of web development and search engine optimization (SEO), ensuring that your website is easily accessible and properly indexed by search engines is paramount. One essential tool that aids in this process is the creation of a robots.txt file. In this comprehensive guide, we, the experts, will walk you through the process of […]
Read More
How to Generate Sitemap in Next JS?
Sep 28, 2023
·8 Min Read
In today’s digital landscape, optimizing your website’s SEO is crucial to attracting more organic traffic and ranking higher on search engine result pages (SERPs). One essential aspect of SEO is creating a sitemap, which helps search engines crawl and index your website efficiently. If you’re using Next JS for your website development, this guide will […]
Read More