Home > other >  How do i implement 'All' in this dropdown filter in React
How do i implement 'All' in this dropdown filter in React

Time:12-01

I want to add this 'All' feature where i can show all expenses at once. For now i can only see filtered expenses by year.

import React from 'react';

import './ExpensesFilter.css';

const ExpensesFilter = (props) => {
    const dropdownChangeHandler = (event) => {
        props.onChangeFilter(event.target.value);
    };
    
    return (
        <div className="expenses-filter">
            <div className="expenses-filter__control">
                <label>Filter by year</label>
                <select value={props.selected} onChange={dropdownChangeHandler}>
                    <option value='2022'>2022</option>
                    <option value='2021'>2021</option>
                    <option value='2020'>2020</option>
                    <option value='2019'>2019</option>
                    <option value='All'>All</option>
                </select>
            </div>
        </div>
    );
};

export default ExpensesFilter;

This is main Expenses.js component where the filtering is applied

function Expenses(props) {
  const [filteredYear,setFilteredYear] = useState('2020');
  
  const filterChangeHandler = selectedYear => {
    setFilteredYear(selectedYear);
  };

  const filteredExpenses = props.items.filter(expense => {
    return expense.date.getFullYear().toString() === filteredYear;
  });

Part 2

return (
    <div>
    <Card className='expenses'>
        <ExpensesFilter selected={filteredYear} onChangeFilter={filterChangeHandler}/>
    <ExpensesChart expenses={filteredExpenses}/>
    <ExpensesList items={filteredExpenses}/>
    </Card>
    </div>);
  };
export default Expenses;

CodePudding user response:

You've got everything you need. The way you have it set up should work with just a minor change. When the selected filter is "All" you don't want to filter the expenses:

const filteredExpenses =
  filteredYear === "All"
    ? props.items
    : props.items.filter((expense) => {
        return expense.date.getFullYear().toString() === filteredYear;
      });

  • Related