Home > Mobile >  React JS filter the product according to year
React JS filter the product according to year

Time:03-25

I wanna filter the products according to the year, I made <ItemDateFilter /> component where I have the <select> menu to select the year. I know the code to compare the date of product with the filtered year here is comparing code:-

const filteredYearValue = productListItems.filter(e => {
    return e.date.getFullYear().toString() === filterValue;
})

but I have few confusions to get the filtered value from ItemDateFilter.js to ProductITems.js.

Here is my code - https://github.com/mohitdevelops/react-lessons/tree/main/product-app

CodePudding user response:

You can move the state from ItemDateFilter component to App Component

// App.js
const [filterValue, setFilterValue] = useState('2022');

function onFilterDateValue(event){
   setFilterValue(event.target.value);                     
}

And pass the onFilterDateValue function to ItemDateFilter component through props

<ItemDateFilter onFilterChange={onFilterDateValue}/>

And filter the list before passing to ProductListItems component

<ProductItems productListItems={productLists.filter(item => item.date.getFullYear() ===  filterValue)}/>

CodePudding user response:

You modify App.js , ProductItems.js, ItemDateFilter.js the following below code

/* App.js*/
import './App.css';
import AddProduct from './components/AddProduct/AddProducts';
import ProductItems from './components/Products/ProductItems/ProductItems';
import ItemDateFilter from './components/ItemDateFilter';
import { useEffect, useState } from 'react';

export default function App() {

  const ALL_PRODUCTS = [
        {
            name: "Titan",
            des: "Look modish by donning this women's watch from the Ceramic Refresher collection by Titan. Enclosed in a 33 mm case, the mother of pearl round dial is secured by a mineral glass. It displays plain three hands and a crown for time adjustment. The ceramic strap showcases a navy hue that uplifts the look of the timepiece. Besides, it is finished with a deployment clasp that provides a secure fit on the wrist.",
            date: new Date(2020, 7, 14),
            price: 360000,
      image: 'https://cdn.pixabay.com/photo/2020/12/04/16/15/watch-5803619__340.jpg',
        },
    {
            name: "Shampoo",
            des: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries",
            date: new Date(2021, 8, 8),
            price: 360,
      image: 'https://img.freepik.com/free-photo/shampoo-bottle-butterfly-pea-flower-put-white-wooden-background_1150-28107.jpg?size=626&ext=jpg&ga=GA1.2.482173369.1648044063',
        },
    {
            name: "Chair",
            des: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web pag",
            date: new Date(2019, 1, 30),
            price: 1400,
      image: 'https://img.freepik.com/free-photo/blue-dining-room-chair-room-with-gray-walls_181624-30430.jpg?size=626&ext=jpg&ga=GA1.2.482173369.1648044063',
        },
    ];

  const [productLists, setProductList] = useState([]);
  const [year,setYear] = useState(null);
  useEffect(()=>{
    setProductList(ALL_PRODUCTS);
   
  },[])

  const newProductAdded = function(productLists){
    setProductList(demoFunc =>{
      return [productLists, ...demoFunc]
    })
  }

  const onChangeYear = (params)=>{
    setYear(params);
    
  }

  return (
    <div className='productsMainWrap'>
      <div className='productsItems'>
        <div className='topBar'>
          <h2>Products</h2>
          {
            productLists.length>0 &&  <ItemDateFilter productListItems = {productLists} selectYear = {onChangeYear} year={year} />

          }
          {
            productLists.length>0 && <ProductItems productListItems={productLists} year={year}/>
          }
         </div>
         
        </div>
        <div className='productsEnteryWrapper'>
        <AddProduct onNewProductAdded={newProductAdded}/>
      </div>   
    </div>
  );
}





/*ProductItems.js*/
import Items from "./Items";
import ItemDateFilter from "../../ItemDateFilter";
import { useEffect, useState } from "react";

export default function ProductItems(props) {
    
    return (
        <div className="productItemsWrapper">
            {props.productListItems.map(function (items) {
                 const month = items.date.getMonth();
                 const day = items.date.toLocaleString("en-US", { day: "2-digit" });
                 const year = items.date.getFullYear();
                 if(props.year==year){
                    return (
                        <Items
                            productName={items.name}
                            productDescription={items.des}
                            productPrice={items.price}
                            productDate={items.date}
                            productImage={items.image}
                        />
                    );
                 }
                 if(props.year==null){
                    return (
                        <Items
                            productName={items.name}
                            productDescription={items.des}
                            productPrice={items.price}
                            productDate={items.date}
                            productImage={items.image}
                        />
                    );
                 }
                 
                    
                
            })}          
        </div>
    );
}



/*ItemDateFilter.js*/

import { useState } from "react"
export default function ItemDateFilter(props){
    const [filterValue, setFilterValue] = useState('2022');
    const Year = [2019,2020,2021,2022];
    function onFilterDateValue(event){
      props.selectYear(event.target.value)                    
    }
    return(
        <div>
            <select onChange={onFilterDateValue}>                                
               {
                   Year.map(y=>{
                       if(y==props.year){
                            return <option value={y} selected>{y}</option>
                       }
                       if(y!=props.year){
                         return <option value={y}>{y}</option>
                       }
                   })
               }
            </select>
        </div>
    )
}

  • Related