"Building a Search Bar to Filter Data from a JSON File in React.js"
To implement a search bar code to filter data from a data.json file in React.js, we will follow these steps:
Assuming you already have a React.js project set up, let's go through each step with code examples:
Step 1: Create a new React component that will handle the search functionality.
import React, { useState } from 'react'
import data from './data.json';
const SearchBarFilter = () => {
const [searchTerm, setSearchTerm] = useState('');
const [filteredData, setFilteredData] = useState(data);
const handleInputChange = (event) => {
const { value } = event.target;
setSearchTerm(value);
filterData(value);
};
const filterData = (searchTerm) => {
const filteredData = data.filter((item) =>
item.name.toLowerCase().includes(searchTerm.toLowerCase())
);
setFilteredData(filteredData);
};
return (
<div>
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={handleInputChange}
/>
<ul>
{filteredData.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
export default SearchBarFilter;
;
Step 2: Assuming you have a data.json file with the following structure:
{
"id": 1,
"name": "Apple"
},
{
"id": 2,
"name": "Banana"
},
{
"id": 3,
"name": "Orange"
},
// Add more items as needed...
]
[
Step 3: Render the SearchBarFilter component in your main application component.
Recommended by LinkedIn
import React from 'react'
import SearchBarFilter from './SearchBarFilter';
const App = () => {
return (
<div>
<h1>Fruit Search</h1>
<SearchBarFilter />
</div>
);
};
export default App;
;
Step 4: With these steps completed, your application will now have a search bar where users can input text. As they type, the data will be filtered based on the input, and the filtered results will be displayed below the search bar.
The handleInputChange function is responsible for capturing the user input in the search bar, updating the searchTerm state, and then calling the filterData function.
The filterData function takes the current searchTerm and uses the filter method to find items that match the search criteria. It performs a case-insensitive search by converting both the search term and item names to lowercase before comparing them.
Finally, the filtered data is stored in the filteredData state, and the ul element displays the names of the items that match the search term.
With these steps, you now have a ready-to-use React.js code that filters data from a data.json file based on user input using a search bar.
Systems Administrator/IT Support
11moThank you, sir!
Front End Developer at Bdcalling
1yThanks a lot