|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import './Filtering.css'; |
| 3 | + |
| 4 | +const Filtering = ({ onFilterChange }) => { |
| 5 | + const [isOpen, setIsOpen] = useState(false); // State to toggle dropdown open/close |
| 6 | + const [selectedOption, setSelectedOption] = useState('Sort by'); // Initial state |
| 7 | + const [sortOrder, setSortOrder] = useState('asc'); // Track sort order (asc/desc) |
| 8 | + |
| 9 | + const toggleDropdown = () => { |
| 10 | + setIsOpen(!isOpen); // Toggle dropdown open/close state |
| 11 | + }; |
| 12 | + |
| 13 | + const toggleSortOrder = () => { |
| 14 | + // Toggle sort order only if an option is selected |
| 15 | + if (selectedOption !== 'Sort by') { |
| 16 | + const newSortOrder = sortOrder === 'asc' ? 'desc' : 'asc'; |
| 17 | + setSortOrder(newSortOrder); |
| 18 | + onFilterChange(selectedOption, newSortOrder); // Trigger filtering with new order |
| 19 | + } |
| 20 | + }; |
| 21 | + |
| 22 | + const handleOptionClick = (option) => { |
| 23 | + // Handle filter option selection |
| 24 | + setSelectedOption(option); |
| 25 | + onFilterChange(option, sortOrder); // Call the parent function with selected filter and order |
| 26 | + setIsOpen(false); // Collapse the dropdown after selection |
| 27 | + }; |
| 28 | + |
| 29 | + return ( |
| 30 | + <div className="filtering-container"> |
| 31 | + <div className="dropdown"> |
| 32 | + {/* Make the entire button clickable for toggling dropdown */} |
| 33 | + <button onClick={toggleDropdown} className="dropdown-toggle"> |
| 34 | + {selectedOption} |
| 35 | + {/* Render the up/down arrow next to selected option */} |
| 36 | + {selectedOption !== 'Sort by' && ( |
| 37 | + <span onClick={(e) => { e.stopPropagation(); toggleSortOrder(); }}> |
| 38 | + {sortOrder === 'asc' ? ' ↑' : ' ↓'} |
| 39 | + </span> |
| 40 | + )} |
| 41 | + <span className="dropdown-arrow">▼</span> |
| 42 | + </button> |
| 43 | + |
| 44 | + {isOpen && ( |
| 45 | + <div className="dropdown-menu"> |
| 46 | + <div onClick={() => handleOptionClick('Date Modified')} className="dropdown-item"> |
| 47 | + Date Modified |
| 48 | + </div> |
| 49 | + <div onClick={() => handleOptionClick('Date Created')} className="dropdown-item"> |
| 50 | + Date Created |
| 51 | + </div> |
| 52 | + <div onClick={() => handleOptionClick('Alphabetical')} className="dropdown-item"> |
| 53 | + Alphabetical |
| 54 | + </div> |
| 55 | + </div> |
| 56 | + )} |
| 57 | + </div> |
| 58 | + </div> |
| 59 | + ); |
| 60 | +}; |
| 61 | + |
| 62 | +export default Filtering; |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
0 commit comments