SearchContext
Description
Provides search result page data to child components. Used only on search result pages to access search keyword, products, and active filters.
Import
import { SearchProvider, useSearch } from '@components/frontStore/catalog/SearchContext';
Usage
Setup Provider
import { SearchProvider } from '@components/frontStore/catalog/SearchContext';
function SearchPage({ searchData }) {
return (
<SearchProvider searchData={searchData}>
{/* Search page components */}
</SearchProvider>
);
}
Access Search Data
import { useSearch } from '@components/frontStore/catalog/SearchContext';
function SearchResults() {
const { keyword, products } = useSearch();
return (
<div>
<h1>Search results for "{keyword}"</h1>
<p>{products.total} products found</p>
</div>
);
}
API
SearchProvider Props
| Name | Type | Required | Description |
|---|---|---|---|
| searchData | SearchPageData | Yes | Search data object |
| children | ReactNode | Yes | Child components |
useSearch Hook
Returns the complete SearchPageData object. Throws error if used outside SearchProvider.
SearchPageData Interface
| Field | Type | Description |
|---|---|---|
| keyword | string | Search keyword/term |
| url | string | Search page URL |
| products | SearchProducts | Product search results |
SearchProducts Interface
interface SearchProducts {
items: ProductData[]; // Array of products
currentFilters: FilterInput[]; // Active filters
total: number; // Total result count
}
Examples
Search Header
import { useSearch } from '@components/frontStore/catalog/SearchContext';
function SearchHeader() {
const { keyword, products } = useSearch();
return (
<div className="search-header">
<h1>Search Results</h1>
<p>
Found <strong>{products.total}</strong> results for "{keyword}"
</p>
</div>
);
}
Product Results
import { useSearch } from '@components/frontStore/catalog/SearchContext';
import { ProductList } from '@components/frontStore/catalog/ProductList';
function SearchResults() {
const { products } = useSearch();
return (
<ProductList
products={products.items}
emptyMessage={`No products found`}
/>
);
}
Related Components
- ProductList - Product listing display
- ProductFilter - Product filtering
- CategoryContext - Category page context
- ProductContext - Single product context