Search code examples
reactjsreduxcategoriesreact-bootstrap

Filtering by categories react and bootstrap


i am building an ecommerce website and i'm trying to add category button on the home page so that when you click a specific category, only those items will show. I am using redux to bring all the items to the home screen.

const products = [
  {
    name: 'Airpods Wireless Bluetooth Headphones',
    image: '/images/airpods.jpg',
    description:
      'Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working',
    brand: 'Apple',
    category: 'Headphones',
    price: 89.99,
    countInStock: 10,
    rating: 4.5,
    numReviews: 12,
  },

The item structure looks like this.

This is the code I have on the HomeScreen component:

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Row, Col, Button, ButtonGroup } from 'react-bootstrap';
import Product from '../components/Product';
import Loader from '../components/Loader';
import Message from '../components/Message';
import { listProducts } from '../actions/productActions';

const HomeScreen = () => {
  const dispatch = useDispatch();

  const productList = useSelector(state => state.productList);
  const { loading, error, products } = productList;

  const allCategories = [
    'All',
    ...new Set(products.map(product => product.category)),
  ];
  console.log(allCategories);

  useEffect(() => {
    dispatch(listProducts());
  }, [dispatch]);

  return (
    <>
      <div className="text-center my-4">
        <ButtonGroup>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            All
          </Button>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            Phones
          </Button>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            Headphones
          </Button>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            Cameras
          </Button>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            Cameras
          </Button>
          <Button className="btn-color-primary" style={{ margin: '5px' }}>
            PlayStation
          </Button>
        </ButtonGroup>
      </div>
      {loading ? (
        <Loader />
      ) : error ? (
        <Message variant="danger">{error}</Message>
      ) : (
        <Row>
          {products.map(product => (
            <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
              <Product product={product} />
            </Col>
          ))}
        </Row>
      )}
    </>
  );
};

export default HomeScreen;

I created a variable that has all the categories from the proeducts mapped plus the 'All' one.What should i add to the Buttons so that when i click on them it would work as wanted?


Solution

  • You can create a state variable that will have the selected category name. Before you render products filter the products which have the category as selected category.

    const [selectedCategory, setSelectedCategory] = useState("All");
    const handleClick = (category) => setSelectedCategory(category);
    

    Now, for the buttons, you should add an onClick event listener which changes the selectedCategory when it is clicked. for eg

    <ButtonGroup>
        {
         allCategories.map(category => (
            <Button onClick={() => handleClick(category)} key={category} className="btn-color-primary" style={{ margin: '5px' }}>
                {category}
            </Button>)
        }
     </ButtonGroup>
    

    Now, filter the products if selectedCategory is not "All"

    products.filter(product => selectedCategory==="All" || product.category===selectedCategory)
        .map(product => (
            <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                <Product product={product} />
            </Col>))