useSelectedVariant
The useSelectedVariant
hook is a React hook designed to manage the selection of a product variant.
Usage
The useSelectedVariant
hook provides methods and values to manage the selection of a product variant.
import { useSelectedVariant } from "builderoo";
const { variant, onSelectOption, isOptionSelected, preferredMedia, setPreferredMedia } = useSelectedVariant(product)
Parameters
Name | Type | Description |
---|---|---|
product | Product | The product object for which the variant selection will be managed. |
initialSelectedVariant | 0 | (optional) The pre-selected variant, if needed. |
Return Values
Name | Type | Description |
---|---|---|
variant | object | The currently selected product variant. |
onSelectOption | function | A function to toggle (set or unset) an option selection. |
isOptionSelected | function | A function to check if a specific variant option is currently selected. |
preferredMedia | Media | The optimal media items from product.media based on user selected options (via onSelectOption() . |
setPreferredMedia | function | Set preferredMedia manually. This state setter can be used to change the value when user manually selects another media. preferredMedia resets when onSelectOption() is called. |
Example
Here’s an example of how to use the useSelectedVariant
hook to manage product variant selection:
import React from 'react';
import { useSelectedVariant } from 'builderoo';
import classNames from "classnames";
function ProductDetail({ product }) {
const { variant, onSelectOption, isOptionSelected } = useSelectedVariant(product);
return (
<div className="product-detail">
<h1>{product.name}</h1>
<p>Price: ${variant.price}</p>
<ul className="space-y-3 mt-4">
{ product.options && product.options.length > 0 && product.options.map((option, i) => (
<li key={i} className="w-20">
<div className="text-sm">{option.name}</div>
<ul className="flex gap-3 mt-1">
{ option.values.map((value, i) => (
<li
onClick={() => onSelectOption(option._id, value._id)}
key={i}
className={classNames(
"border border-gray-300 rounded-sm px-3 py-1 text-sm cursor-pointer",
{"bg-black text-white": isOptionSelected(value._id)},
{"bg-muted-background text-black": !isOptionSelected(value._id)},
)}>
{value.label}
</li>
))}
</ul>
</li>
))}
</ul>
</div>
);
}
export default ProductDetail;
In this example, the ProductDetail
component uses the useSelectedVariant
hook to manage the selection
of a product variant. It displays the product’s name, price, and a list of variant options as buttons.
The onSelectOption
function allows users to select a variant, and isOptionSelected
checks
if an option is currently selected.