Create Category Filters using React and Tailwind CSS
Last Updated :
27 Sep, 2024
Creating a category filter in a React application allows users to filter a list of items based on selected categories. We will build a simple filtering system using React for state management and Tailwind CSS for styling and React Icons to add visual enhancements to the UI. This project will allow users to click on category buttons dynamically filtering content based on their selection.
Prerequisites
Approach
You can implement a straightforward filtering system by setting up an array of categories and items. First, create a list of categories, each paired with an icon for a more interactive UI. Using React’s useState, manage the currently selected category. When a category is clicked, update the state to reflect the selection and filter the items displayed based on that category. Tailwind CSS helps in styling the buttons, making them responsive, with hover effects and dynamic background colors that change depending on the selection. Finally, the filtered items are displayed in a grid layout, ensuring they adapt beautifully across different screen sizes
Steps to Create & Configure the Project
Here we will create a sample React JS project then we will install Tailwind CSS once it is completed we will start development for Category Filters using React and Tailwind CSS. Below are the steps to create and configure the project.
Step 1: Set up a React Application
First, create a sample React JS application by using the mentioned command then navigate to the project folder
npx create-react-app react-app
cd react-app
Project Structure:
project fStructureUpdated Dependencies:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Step 2: Install and Configure Tailwind CSS
Once Project is created successfully Now install and configure the Tailwind css by using below commands in your project.
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
npm install react-icons
Step 3: Develop Business logic
Once Tailwind css installation and configuration is completed. Now we need to develop user interface for Category Filters using tailwind CSS and for making it responsive we will use App.js and App.css files.
- App.js ( src\App.js )
- index.css ( src\index.js )
- tailwind.config.js ( tailwind.config.js )
Example: This demonstrates the creation of Category Filters using React and Tailwind CSS
CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
margin: 0;
font-family: 'Times New Roman', Times, serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
h2 {
margin-top: 2rem; /* Adjust top margin for spacing */
}
JavaScript
//App.js
import React, { useState } from "react";
import { FaMusic, FaLaptop, FaTshirt, FaMobileAlt } from "react-icons/fa";
import 'tailwindcss/tailwind.css';
const categories = [
{ name: "All", icon: null },
{ name: "Music", icon: <FaMusic /> },
{ name: "Tech", icon: <FaLaptop /> },
{ name: "Fashion", icon: <FaTshirt /> },
{ name: "Mobile", icon: <FaMobileAlt /> },
];
const items = [
{ id: 1, name: "Guitar", category: "Music" },
{ id: 2, name: "Laptop", category: "Tech" },
{ id: 3, name: "T-shirt", category: "Fashion" },
{ id: 4, name: "iPhone", category: "Mobile" },
{ id: 5, name: "Piano", category: "Music" },
{ id: 6, name: "Smartwatch", category: "Tech" },
{ id: 7, name: "Jeans", category: "Fashion" },
{ id: 8, name: "Headphones", category: "Music" },
];
function App() {
const [selectedCategory, setSelectedCategory] = useState("All");
const filterItems = () => {
if (selectedCategory === "All") {
return items;
}
return items.filter(item => item.category === selectedCategory);
};
return (
<div className="container mx-auto p-5">
<h1 className="text-3xl font-bold
mb-6 text-center">Category Filters</h1>
<div className="flex justify-center space-x-4 mb-6">
{categories.map(category => (
<button
key={category.name}
onClick={() => setSelectedCategory(category.name)}
className={`px-4 py-2 rounded-lg flex
items-center
space-x-2 border ${selectedCategory === category.name
? "bg-green-500 text-white"
: "bg-white text-black"
} hover:bg-green-300 transition`}
>
{category.icon && <span>{category.icon}</span>}
<span>{category.name}</span>
</button>
))}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2
md:grid-cols-3 lg:grid-cols-4 gap-4">
{filterItems().map(item => (
<div key={item.id} className="p-4 border rounded-lg
shadow-lg bg-slate-300">
<h2 className="text-xl font-semibold">{item.name}</h2>
<p className="text-gray-500">{item.category}</p>
</div>
))}
</div>
</div>
);
}
export default App;
JavaScript
/*src/tailwind.congif.js*/
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
extend: {
colors: {
primaryGreen: "#4CAF50", // Green
primaryBlack: "#000000", // Black
primaryWhite: "#FFFFFF", // White
}
},
},
plugins: [],
}
Step 4: Run the Application
Once Development is completed Now we need run the react js application by using below command. By default the react js application run on port number 3000.
npm start
Output: Once Project is successfully running then open the below URL to test the output.
http://localhost:3000/
Conclusion
By using React for functionality Tailwind CSS for styling and React Icons for visual enhancement, we can build an efficient and dynamic category filtering system. This project can be expanded with more complex filtering logic and additional UI elements as required.
Similar Reads
Create Category Previews Using React And Tailwind CSS
In modern web development creating visually appealing and functional components is essential for enhancing user experience. The goal is to showcase categories with distinct icons and a stylish green background using Tailwinds utility classes for a streamlined and responsive design.This article focus
4 min read
Create Footers Using React And Tailwind CSS
We will learn how to create a responsive footer using React and Tailwind CSS with a modern design. The footer will feature a green background with white text providing a clean and professional look. We will create three sections: Contacts social media and Services to display important information an
3 min read
Create FAQs using React and Tailwind CSS
A Frequently Asked Questions section is a common feature found on websites and applications that helps users find answers to common queries in an organized manner. A well-designed FAQ can improve user experience reduce support requests and provide users with quick and easy access to helpful informat
5 min read
Create Flyout Menus using React and Tailwind CSS
Flyout menus are a type of navigational menu that can be displayed when the user hovers over or clicks on an item allowing for a clean and organized display of additional options without crowding the main interface. In this article, we will create a responsive flyout menu using React and Tailwind CS
4 min read
Create Banners using React and Tailwind CSS
We will build a responsive banner component using React and Tailwind CSS. Tailwind CSS allows us to create highly customizable and modern UI components with minimal effort. The banner will include a heading and subheading and a call to action button styled for responsiveness and accessibility.Prereq
3 min read
Create Incentives using React and Tailwind CSS
Creating an Incentives section in a web application can be a great way to highlight special offers and rewards or bonuses that motivate users to engage with your product or service. This feature can be used in various scenarios such as e-commerce websites educational platforms or company portals. In
4 min read
Create Header using React and Tailwind CSS
In modern web development building responsive and customizable user interfaces is crucial. One of the essential elements of any web application is the header which typically contains navigation links branding or other important controls. we will create a responsive header section using React and Tai
4 min read
Create Logo Clouds using React and Tailwind CSS
A Logo Cloud is a webpage section that displays logos of partners, sponsors, clients, or technologies in a visually appealing way. This component is often used to establish credibility or showcase affiliations. Using React and Tailwind CSS you can create a responsive and customizable logo cloud that
3 min read
Create Feeds UI using React and Tailwind CSS
In the world of social networking, feeds are the primary way users interact with content. Whether it is on LinkedIn, Facebook, or Twitter the feed showcases posts updates, and activities from people or organizations. This article will help you build a LinkedIn-style feed UI using React and Tailwind
4 min read
Create Command Palettes UI using React and Tailwind CSS
This article shows you how to create a Command Palette UI using React and Tailwind CSS. A command palette lets users easily search for and run commands within an app, making navigation faster and more efficient. Weâll walk you through building a simple and intuitive interface where users can type, s
4 min read