Let's create a filter component using React, MobX, and GraphQL. This example will demonstrate a product filter system with categories and price ranges, but you can adapt it to your specific needs.
First, let's set up the necessary dependencies and structure:
Install required packages:
bash Copy code
npm install mobx mobx-react @apollo/client graphql
Here's the complete implementation:
First, create a MobX store for managing filter state (stores/FilterStore.js):
javascript Copy code
import { makeAutoObservable } from 'mobx';
class FilterStore {
selectedCategories = [];
priceRange = { min: 0, max: 1000 };
searchQuery = '';
constructor() {
makeAutoObservable(this);
}
setCategories(categories) {
this.selectedCategories = categories;
}
setPriceRange(min, max) {
this.priceRange = { min, max };
}
setSearchQuery(query) {
this.searchQuery = query;
}
get filterParams() {
return {
categories: this.selectedCategories,
priceRange: this.priceRange,
searchQuery: this.searchQuery,
};
}
resetFilters() {
this.selectedCategories = [];
this.priceRange = { min: 0, max: 1000 };
this.searchQuery = '';
}
}
export default new FilterStore();
Create GraphQL queries (graphql/queries.js):
javascript Copy code
import { gql } from '@apollo/client';
export const GET_CATEGORIES = gql`
query GetCategories {
categories {
id
name
}
}
`;
export const GET_FILTERED_PRODUCTS = gql`
query GetFilteredProducts($filters: ProductFilterInput!) {
products(filters: $filters) {
id
name
price
category {
id
name
}
}
}
`;
Create the Filter Component (components/FilterComponent.js):
Create a Product List Component to use the filters (components/ProductList.js):
javascript Copy code
import React from 'react';
import { observer } from 'mobx-react';
import { useQuery } from '@apollo/client';
import filterStore from '../stores/FilterStore';
import { GET_FILTERED_PRODUCTS } from '../graphql/queries';
const ProductList = observer(() => {
const { loading, error, data } = useQuery(GET_FILTERED_PRODUCTS, {
variables: { filters: filterStore.filterParams },
});
if (loading) return <div>Loading products...</div>;
if (error) return <div>Error loading products: {error.message}</div>;
return (
<div className="product-list">
<h2>Products</h2>
{data.products.length === 0 ? (
<p>No products found</p>
) : (
<div className="products-grid">
{data.products.map((product) => (
<div key={product.id} className="product-card">
<h3>{product.name}</h3>
<p>Price: ${product.price}</p>
<p>Category: {product.category.name}</p>
</div>
))}
</div>
)}
</div>
);
});
export default ProductList;
Create the main App component (App.js):
javascript Copy code
import React from 'react';
import { ApolloProvider } from '@apollo/client';
import { createHttpLink } from '@apollo/client';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import FilterComponent from './components/FilterComponent';
import ProductList from './components/ProductList';
// Setup Apollo Client
const client = new ApolloClient({
link: createHttpLink({
uri: 'YOUR_GRAPHQL_ENDPOINT', // Replace with your GraphQL endpoint
}),
cache: new InMemoryCache(),
});
function App() {
return (
<ApolloProvider client={client}>
<div className="app">
<h1>Product Filter Demo</h1>
<div className="main-container">
<div className="filter-sidebar">
<FilterComponent />
</div>
<div className="product-content">
<ProductList />
</div>
</div>
</div>
</ApolloProvider>
);
}
export default App;
Add some basic CSS (styles.css):
css Copy code
.app {
padding: 20px;
}
.main-container {
display: flex;
gap: 20px;
}
.filter-sidebar {
width: 300px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
.filter-section {
margin-bottom: 20px;
}
.filter-option {
margin: 5px 0;
}
.price-range {
display: flex;
gap: 10px;
align-items: center;
}
.price-range input {
width: 100px;
}
.reset-button {
padding: 8px 16px;
background-color: #f44336;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.product-content {
flex: 1;
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.product-card {
padding: 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
To use this implementation:
Make sure you have a GraphQL server running with the appropriate schema and resolvers.
Replace 'YOUR_GRAPHQL_ENDPOINT' in the Apollo Client setup with your actual GraphQL endpoint.
The GraphQL schema should support the queries defined in queries.js.
The filter component will automatically update the product list when filters change, thanks to MobX's reactivity.
Key features of this implementation:
Uses MobX for state management of filters
Uses Apollo Client for GraphQL queries
Observer pattern for automatic re-rendering
Responsive filter updates
Reset functionality
Error and loading states handling
Reusable component structure
You can extend this further by:
Adding debouncing for search input
Implementing more filter types (e.g., rating, brand, etc.)
Adding sorting options
Implementing pagination
Adding filter persistence (localStorage)
Adding more advanced price range sliders
Remember to handle edge cases and add appropriate error boundaries in a production environment.