import React, { useState, useEffect } from 'react';
const ProductFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
categories: [],
selectedCategory: 'all',
sortBy: 'newest'
};
}
componentDidMount() {
// Fetch product categories from the API
fetch('/api/categories')
.then(res => res.json())
.then(data => this.setState({ categories: data }));
}
handleCategoryChange = (e) => {
this.setState({ selectedCategory: e.target.value });
}
handleSortChange = (e) => {
this.setState({ sortBy: e.target.value });
}
render() {
const { categories, selectedCategory, sortBy } = this.state;
return (
<div className="product-filter">
<label>
Category:
<select value={selectedCategory} onChange={this.handleCategoryChange}>
<option value="all">All</option>
{categories.map(category => (
<option key={category.id} value={category.id}>{category.name}</option>
))}
</select>
</label>
<label>
Sort by:
<select value={sortBy} onChange={this.handleSortChange}>
<option value="newest">Newest</option>
<option value="price-asc">Price (Low to High)</option>
<option value="price-desc">Price (High to Low)</option>
</select>
</label>
</div>
);
}
}
export default ProductFilter;