Notes
![]() ![]() Notes - notes.io |
import Link from "next/link";
import React, { useState, useEffect } from "react";
import { apiUrl } from "@/app/constant/constant";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
const ProductFilter = () => {
const { t } = useTranslation();
const [productFilterData, setProductFilterData] = useState([]);
const [categoryAttribute, setCategoryAttribute] = useState([]);
const [productAttribute, setProductAttribute] = useState([]);
const [compareData, setCompareData] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [filteredProductData, setFilteredProductData] = useState([]);
const [filterwise, setFilterWise] = useState([]);
const [checkboxArray, setCheckBoxArray] = useState([]);
const [checkbox, setCheckBox] = useState([]);
const handleCheckboxChange = (event, productAttr) => {
let updatedArray;
if (event.target.checked === true) {
// Add the value to the checkboxArray
updatedArray = [...checkboxArray, productAttr];
} else {
// Remove the value from the checkboxArray
updatedArray = checkboxArray.filter((attr) => attr !== productAttr);
}
setCheckBoxArray(updatedArray);
setCheckBox(updatedArray);
setFilteredProductData(updatedArray);
console.log("Update data:", filteredProductData);
};
//state variables are declared using useState hook
const handleSelectClick = (productId) => {
console.log(productId);
const selectedProducts = productFilterData.map((item) =>
item.id === productId ? { ...item, isSelected: !item.isSelected } : item
);
setProductFilterData(selectedProducts);
};
const router = useRouter();
//router Initialization
const handleCompareClick = () => {
//when compare button click it navigate to compare component
const selectedProductIds = productFilterData
.filter((item) => item.isSelected === true)
.map((item) => item.id);
setCompareData(selectedProductIds);
//console.log(selectedProductIds);
localStorage.setItem(
"selectedProductItemsIds",
JSON.stringify(selectedProductIds)
);
router.push("/compare");
};
function getFilterWiseCheckedBox() {
const selectedProductIds = checkboxArray.map(
(item) => item.attribute_values
);
console.log("Selected Product Ids:", selectedProductIds);
const categoryIds = JSON.parse(localStorage.getItem("selectedCatIds"));
//console.log(selectedProductIds);
const lang = null;
fetch(`${apiUrl}api/product/filterwise`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
filter_values: selectedProductIds,
category_ids: categoryIds,
lang: lang,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log("product/filterwise-api", responseJson);
if (responseJson.success === "true") {
setFilterWise(responseJson.filter_product);
} else {
console.error("Error in filterwise API:", responseJson.message);
}
})
.catch((error) => {
console.error("Error fetching filterwise data:", error);
});
}
useEffect(() => {
getFilterWiseCheckedBox();
}, []);
function getAllProductsCategoryWise() {
const ids = JSON.parse(localStorage.getItem("selectedCatIds"));
const obj = { category_ids: ids };
fetch(`${apiUrl}api/product/categorywise`, {
method: "POST",
body: JSON.stringify(obj),
headers: {
"Content-Type": "application/json",
},
// body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
//console.log(responseJson)
if (responseJson.success === "true") {
//setProductData(responseJson.data);
const flatArray = responseJson.data.flat();
setProductFilterData(flatArray);
setFilteredProductData(flatArray);
setCategoryAttribute(responseJson.category_attribute);
setProductAttribute(responseJson.product_attr_value);
//console.log(responseJson.product_attr_value)
}
})
.catch((error) => {
//console.error(error);
// toast.error(error, {
// position: toast.POSITION.TOP_CENTER,
// });
alert("Please select the product");
});
}
useEffect(() => {
//Hook to Fetch Data on Component Mount
getAllProductsCategoryWise();
}, [checkbox]);
//here dependency array []is empty which indicates it should run only once
const handleSearchChange = (event) => {
//search filter
const query = event.target.value;
setSearchQuery(query);
const filteredData = productFilterData.filter((item) => {
const name = item.pro_name || "";
const details = item.pro_details || "";
return (
name.toLowerCase().includes(query.toLowerCase()) ||
details.toLowerCase().includes(query.toLowerCase())
);
});
setFilteredProductData(filteredData);
};
return (
<>
<section
className="banner"
style={{
backgroundImage: `url(/assets/img/banner3.jpg)`,
backgroundSize: "cover", // You can adjust these styles as needed
backgroundRepeat: "no-repeat",
width: "100%",
height: "540px", // Set the width and height as needed
}}
>
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="banner-caption">
<h3>{t("Product with filter")}</h3>
<ul className="breadcrumb">
<li>
<Link href="/">{t("Start")}</Link>
</li>
<li>{t("Product")}</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<section className="service py-100">
<div className="container-fluid">
<div className="row">
<div className="col-md-3 col-lg-2">
<div className="sidebar-header">
<h3>Filter</h3>
<Link href="#">Collapse all</Link>
</div>
<div className="search">
<form action="">
<input
type="search"
name="categoryAttr"
id="categoryAttr"
placeholder="Keyword"
value={searchQuery}
onChange={handleSearchChange}
/>
<button>
<i className="jki jki-search-light"></i>
</button>
</form>
</div>
<div className="sidebar">
{categoryAttribute.length &&
categoryAttribute.map((categoryAttr) => (
<div key={categoryAttr?.attr_name}>
<div className="sidebar"></div>
<h3 className="mt-3">
{categoryAttr?.attr_name}{" "}
<Link href="#">
<i className="jki jki-chevron-down-light"></i>
</Link>
</h3>
{productAttribute.length &&
productAttribute.map((productAttr) =>
categoryAttr.attributes_id ===
productAttr.attributes_id ? (
<div
className="sidebar-inpup"
key={productAttr?.attribute_values}
>
<div className="form-group">
<input
type="checkbox"
id={`a1_${productAttr?.attributes_id}`}
name=""
value=""
onChange={(event) =>
handleCheckboxChange(event, productAttr)
}
/>
<label
htmlFor={`a1_${productAttr?.attributes_id}`}
>
{productAttr?.attribute_values}
</label>
</div>
</div>
) : null
)}
</div>
))}
</div>
</div>
<div className="col-md-8 col-lg-9 col-xl-10 mt-5 mt-md-0">
<div className="row justify-content-center">
<div className="col-md-8">
<div className="about-2-title mb-20 text-center wow fadeInUp">
<span className="section-id">Vergleich</span>
<h2 className="s-52 mb-30">
We Have <span>Many Service</span> Currentrly
</h2>
<p className="mb-0 black">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
Quaerat alias possimus vitae. Eveniet dicta voluptatem
voluptatibus soluta vero enim iusto maxime cum corrupti
odio nemo sed eaque velit, vitae similique!
</p>
</div>
</div>
</div>
<div className="row">
{filteredProductData.length &&
filteredProductData.map((data) => (
//Rendering Product Filter Data
//Product filter data is mapped to JSX elements for rendering.
//The map function is used to iterate over the productFilterData array.
<div
className="col-md-3"
key={`${data.id}`}
onClick={() => handleSelectClick(data.id)}
>
<div
className={`vergleich wow fadeInUp ${
data.isSelected ? "active" : ""
}`}
>
<div className="img-style">
<img
src={`${apiUrl}storage/product/${data?.pro_image}`}
alt=""
className="img-fluid"
/>
</div>
<div
className={`content-style ${
data.isSelected ? "active" : ""
}`}
>
<h3>{data?.pro_name}</h3>
<p>{data?.pro_details}</p>
</div>
</div>
</div>
))}
</div>
<button className="btn btn-success" onClick={handleCompareClick}>
Compare
</button>
</div>
</div>
</div>
</section>
</>
);
};
export default ProductFilter;
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team