How to filter data in reactjs based on category

 

We can use JavaScript filter method to filter data

For data I am going to create a data.js file and put here some product object inside array like bellow but you can call api or something like this what are you need.

 

data.js


export default [

  {
    id: 1,
    name: "Phone",
    category: "phone",
    price: 333,
  },
  {
    id: 2,
    name: "Laptop",
    category: "laptop",
    price: 533,
  },
  {
    id: 3,
    name: "iMac",
    category: "desktop",
    price: 633,
  }

];

 

Now I am going to create a component called Mobile.jsx and import data.js file to use. Inside useState hook applay filter method to filtering product based on product category

 

Mobile.jsx

import React, {useState } from "react";
import data from "data";
export default function Mobile() {
  const [products, setProduct] = useState(data.filter((x) => x.category == "phone"));
  
  return (
    <>
   
      <h1>Display Sorted Products</h1>
      <div>
        {products &&
          products.map((product) => {
            return (
              <div key={product.id}>
                <div>
                  <img src={product.img} height={300} width={280}></img>
                </div>
                <div>
                  <p>Name: {product.name}</p>
                  <p>Price: {product.price}</p>
                  <button type="button">Add to cart</button>
                </div>
              </div>
            );
          })}
      </div>
    </>
  );
}

 

About Author

Photo

Hi, I am Mahbub Hasan
Software Engineer

I am very much interested to share my programming
and development knowledge with the people.I will try
to update my blog everyday with new technology inshallah.

Thank You

For Visiting My Blog.

Contact Me