useSorting
Overview
The useSorting
hook provides a way to manage and update the sorting state in your application using the Unbxd ReactJS SDK.
Usage
import { useSorting } from "@unbxd-ui/react-search-hooks";
⚠️
Note:
The useSorting hook must be used within the wrapper (in CSR, SSR and Custom Hooks approaches) to ensure that the respective component(s) and the search functionality work properly.
Code Example
import { useSorting } from "@unbxd-ui/react-search-hooks";
const SortComponent = () => {
const { sort, setSort } = useSorting();
const options = [
{ label: "High to Low", value: "price desc" },
{ label: "Low to High", value: "price asc" }
]
const handleSortClick = (value) => {
setSort(value)
}
return <div className="sort-wrapper">
{options.map(option => {
return <div className={`sort-button ${option.value === sort ? "selected": ""}`} onClick={() => { handleSortClick(option.value) }}>
{option.label}
</div>
})}
</div>
};
Hook API
Return Values
- The current sort value for the products.
- Default value -
""
.
- The function to change the sort value, which will be applied to the products.
- Code example -
const handleSortChange = (sortValue) => {
// Based on the passed value, the products will be sorted accordingly.
setSort(sortValue);
};
const renderSortComponent = () => {
return (
<div>
<select
value={sort}
onChange={(event) => {
handleSortChange(event.target.value);
}}>
<option value="">Default</option>
<option value="price_asc">Price: Low to High</option>
<option value="price_desc">Price: High to Low</option>
</select>
</div>
);
};