In this tutorial, we will be building an insane multi-filter feature for your next project using React Js. This feature will allow users to filter through a list of items based on various criteria such as color, size, price, and more. By the end of this tutorial, you will have a fully functioning multi-filter feature that can be easily integrated into any React project.
To get started, make sure you have Node.js and npm installed on your machine. If not, you can download and install them from the official Node.js website. Once you have Node.js and npm installed, you can create a new React project by running the following command in your terminal:
npx create-react-app multi-filter-app
This will create a new React project called multi-filter-app in your current directory. Once the project is created, navigate to the project directory by running:
cd multi-filter-app
Next, install the necessary dependencies for our project by running:
npm install react-icons react-select
React-icons is a library that provides a wide range of icons that we can use in our project, while react-select is a library that allows us to create customizable select dropdowns.
Now that we have set up our project, let’s start by creating a new component for our multi-filter feature. Create a new file called MultiFilter.js in the src/components directory and add the following code:
import React from 'react';
import { useState } from 'react';
import Select from 'react-select';
import { FaTimes } from 'react-icons/fa';
const MultiFilter = ({ items, setFilteredItems }) => {
const [filters, setFilters] = useState([]);
const handleFilterChange = (selectedOption, filterKey) => {
const newFilters = [...filters];
const existingFilterIndex = newFilters.findIndex(filter => filter.key === filterKey);
if (selectedOption) {
if (existingFilterIndex !== -1) {
newFilters[existingFilterIndex] = { key: filterKey, value: selectedOption.value };
} else {
newFilters.push({ key: filterKey, value: selectedOption.value });
}
} else {
newFilters.splice(existingFilterIndex, 1);
}
setFilters(newFilters);
filterItems();
};
const filterItems = () => {
let filteredItems = items;
filters.forEach(filter => {
filteredItems = filteredItems.filter(item => item[filter.key] === filter.value);
});
setFilteredItems(filteredItems);
};
const clearFilters = () => {
setFilters([]);
setFilteredItems(items);
};
return (
<div>
{filters.map((filter, index) => (
<div key={index} className="filter">
<span>{filter.key}: {filter.value}</span>
<button onClick={() => handleFilterChange(null, filter.key)}><FaTimes /></button>
</div>
))}
<div className="filter-select">
<Select
options={[
{ label: 'Red', value: 'red' },
{ label: 'Blue', value: 'blue' },
{ label: 'Green', value: 'green' }
]}
onChange={selectedOption => handleFilterChange(selectedOption, 'color')}
placeholder="Filter by color"
isClearable={true}
/>
</div>
<button onClick={clearFilters}>Clear Filters</button>
</div>
);
};
export default MultiFilter;
In this code, we are creating a new functional component called MultiFilter that takes in two props: items, which is an array of items to filter, and setFilteredItems, which is a function to set the filtered items in the parent component. Inside the component, we are using the useState hook to manage the filters state.
The handleFilterChange function is responsible for updating the filters state when a new filter option is selected or removed. The filterItems function filters the items based on the selected filters and sets the filteredItems state in the parent component.
The clearFilters function resets the filters state and sets the filteredItems state back to the original list of items.
Next, let’s create a new component called ProductsList.js in the src/components directory and add the following code:
import React from 'react';
const ProductsList = ({ items }) => {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item.name} - {item.color} - {item.size} - {item.price}</li>
))}
</ul>
);
};
export default ProductsList;
This component will display the list of filtered items with their name, color, size, and price.
Now, let’s create the main App component in the src directory and add the following code:
import React, { useState } from 'react';
import MultiFilter from './components/MultiFilter';
import ProductsList from './components/ProductsList';
const App = () => {
const items = [
{ name: 'Item 1', color: 'red', size: 'small', price: 10 },
{ name: 'Item 2', color: 'blue', size: 'medium', price: 20 },
{ name: 'Item 3', color: 'green', size: 'large', price: 30 },
{ name: 'Item 4', color: 'red', size: 'medium', price: 15 },
{ name: 'Item 5', color: 'blue', size: 'small', price: 25 },
{ name: 'Item 6', color: 'green', size: 'large', price: 35 },
];
const [filteredItems, setFilteredItems] = useState(items);
return (
<div>
<h1>Multi Filter Feature</h1>
<MultiFilter items={items} setFilteredItems={setFilteredItems} />
<ProductsList items={filteredItems} />
</div>
);
};
export default App;
In this code, we have defined a list of items with their name, color, size, and price. We are using the MultiFilter component to add a multi-filter feature to our application, and the ProductsList component to display the filtered items.
Finally, update the App.js file in the src directory to render the App component:
import React from 'react';
import App from './App';
function App() {
return (
<div className="App">
<App />
</div>
);
}
export default App;
Now, run the following command in your terminal to start the development server:
npm start
Open your browser and navigate to http://localhost:3000 to see the multi-filter feature in action. You should see a list of items with a dropdown to filter items by color, along with a button to clear the filters.
Congratulations! You have successfully built an insane multi-filter feature for your React project. You can further customize the filters and items based on your requirements to create a powerful filtering system for your application. Happy coding!
Build 16 Medium/Hard JavaScript projects for live coding Interview rounds
Get it now- https://xplodivity.graphy.com/courses/16-js-projects-65883553e4b08ebe75f39885
Full Video Preview of each project from the course- https://www.youtube.com/watch?v=coZucJEvsSk
What you'll get:
– Lifetime access
– Full video explanations of building each project from scratch
– 10+ hours of premium content
– Step-by-step explanations and code walkthroughs
– No bullshit, No time waste
– This project list Should get you ready for any JavaScript live coding interview round.
– Extremely cheap (You'll be surprised)
– Practical tips and strategies for mastering JavaScript
– Confidence in handling technical interviews
– Enhanced JavaScript proficiency
Content list:
1. File Explorer (similar to vs-code)
2. Infinitely Nested comments
3. Advanced Custom Toast notification from scratch
4. Drag & Drop, Swap, Add and delete elements using JavaScript
5. Custom Calendar/Date-picker
6. Multi-Select dropdown with support to add & remove elements
7. Build a Memory game with all rules integrated
8. Build an analog clock with smooth animation
9. Dynamic Progress bar with custom input support
10. Build a Star rating system with dynamic hover effects
11. Build a tic tac toe game with best practices
12. Advanced To-Do List with Local Storage support
13. Accordion with smooth transition effects
14. Countdown timer & days remaining timer
15. Create a custom modal
16. Build an optimised Chessboard
love how straight forward your videos are.
Nicely explained. Exactly what I was looking for
how can I select Prada and Gucci at the same time?
Hi. Can you please tell me how to add display of icons like lucide to filter buttons?
You have one field with a name. I can't figure out how to make two values: "Icon" and "el".
how to run this in visual studio pls make a vid i have trying to run from last 2 days plsss di=o it plssss! i am getting so many erros i tried everyhting npm start npm audit npm audit fixes etc to solve issuesðŸ˜
Just what I was looking for. Thank you!
sir, actually in my ecommerce project i am using useSearchParams hook of react router to filter products, but using this, i cant handle multi filter at a same time, it replace the quarry string of the last applied filter, it doesnot concatenate the the quarry sting, can u suggest how can i fix this?
good job!
Exactly the function I am looking for. Now I need to try to figure out how I can use it.
very helpful keep up these short tuts.
awesome!
This is awesome, thank you!
This in not nextjs. just basic filter
Nice one. Especially multi selection. Subbed