
Adding a search bar to your website can significantly improve user experience, allowing visitors to quickly find the content they’re looking for.
In this tutorial, we’ll walk through the process of creating a simple yet effective search bar in React, complete with input handling and dynamic filtering.
What We’ll Build
We’ll create a React component that features:
- An input field for user queries.
- State management to store the search term.
- A list of items that will be filtered based on the search term.
- Dynamic rendering of filtered results.
Prerequisites
Before we begin, make sure you have:
- Node.js and npm (or yarn) installed on your machine.
- A basic understanding of React fundamentals (components, props, state, hooks).
Step 1: Set Up Your React Project (if you don’t have one)
If you don’t have an existing React project, you can quickly create one using
Create React App:
npx create-react-app react-search-bar-tutorial
cd react-search-bar-tutorial
npm start
This will create a new React project and open it in your browser.
Step 2: Create the SearchBar
Component
Inside your src
folder, create a new file called SearchBar.js
. This will house our main search bar logic.
// src/SearchBar.js
import React, { useState } from 'react';
import './SearchBar.css'; // We'll create this CSS file later
function SearchBar({ data }) {
const [searchTerm, setSearchTerm] = useState('');
const [filteredData, setFilteredData] = useState(data);
const handleSearchChange = (event) => {
const term = event.target.value;
setSearchTerm(term);
// Filter the data based on the search term
const results = data.filter((item) =>
item.toLowerCase().includes(term.toLowerCase())
);
setFilteredData(results);
};
return (
<div className="search-container">
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={handleSearchChange}
className="search-input"
/>
<div className="search-results">
{filteredData.length > 0 ? (
<ul>
{filteredData.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
) : (
<p>No results found.</p>
)}
</div>
</div>
);
}
export default SearchBar;
Code Breakdown:
useState('')
: This hook initializessearchTerm
to an empty string. This state variable will hold the current value of our input field.useState(data)
: This hook initializesfilteredData
with thedata
prop passed to the component. This will be the list of items we display after filtering.handleSearchChange
: This function is called every time the input value changes.- It updates
searchTerm
with the new input value. - It then filters the original
data
array.item.toLowerCase().includes(term.toLowerCase())
performs a case-insensitive search. - Finally,
setFilteredData
updates the displayed results.
- It updates
- The
return
statement renders aninput
field and adiv
to display thefilteredData
. We conditionally render a message if no results are found.
Step 3: Add Some Basic Styling
Create a file named SearchBar.css
in the src
folder:
/* src/SearchBar.css */
.search-container {
margin: 20px;
text-align: center;
}
.search-input {
padding: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
.search-results {
margin-top: 20px;
border: 1px solid #eee;
padding: 15px;
border-radius: 5px;
max-width: 300px;
margin-left: auto;
margin-right: auto;
background-color: #f9f9f9;
max-height: 200px; /* Limit height for scrollability */
overflow-y: auto; /* Enable vertical scrolling */
}
.search-results ul {
list-style: none;
padding: 0;
margin: 0;
}
.search-results li {
padding: 8px 0;
border-bottom: 1px solid #eee;
text-align: left;
}
.search-results li:last-child {
border-bottom: none;
}
Feel free to customize these styles to match your website’s design.
Step 4: Integrate SearchBar
into App.js
Now, let’s use our SearchBar
component in the main App.js
file.
// src/App.js
import React from 'react';
import SearchBar from './SearchBar';
import './App.css'; // Optional: for general app styling
function App() {
// Example data to search through
const myData = [
'Apple',
'Banana',
'Cherry',
'Date',
'Elderberry',
'Fig',
'Grape',
'Honeydew',
'Kiwi',
'Lemon',
'Mango',
'Nectarine',
'Orange',
'Pineapple',
'Quince',
'Raspberry',
'Strawberry',
'Tangerine',
'Ugli fruit',
'Vanilla bean',
'Watermelon',
'Xigua', // Chinese watermelon
'Yellow passion fruit',
'Zucchini'
];
return (
<div className="App">
<h1>My Awesome Search App</h1>
<SearchBar data={myData} />
</div>
);
}
export default App;
Here, we define a sample myData
array, which will be the list of items our search bar filters. We then pass this array as a data
prop to our SearchBar
component.
Step 5: Run Your Application
Save all your files and go back to your terminal. If your development server isn’t already running, start it:
npm start
Your browser should open (or refresh) and display the search bar. Try typing into the input field, and you’ll see the list of fruits filter dynamically!
Conclusion and Next Steps
Congratulations! You’ve successfully built a dynamic search bar in React. This basic structure is highly adaptable and can be extended for more complex use cases.
Here are some ideas for further improvements:
- Debouncing: For performance, especially with large datasets or API calls, implement debouncing to delay the search filtering until the user stops typing for a short period.
- API Integration: Instead of a local array, fetch data from an API and then filter it.
- Advanced Filtering: Add more sophisticated filtering options, like filtering by multiple criteria or categories.
- Search Suggestions: Implement a feature that suggests common search terms as the user types.
- Accessibility: Ensure your search bar is accessible to users with disabilities by adding ARIA attributes.
- Styling Libraries: Use a CSS framework like Bootstrap, Material-UI, or Tailwind CSS for more robust styling.
A search bar is a fundamental feature for many applications, and by mastering its creation in React, you’ve added a valuable tool to your development toolkit.
Have any questions about this code? If so leave them in the comments section below!