forked from sanity-io/hydrogen-sanity-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkProduct.client.jsx
40 lines (33 loc) · 921 Bytes
/
LinkProduct.client.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import {Link, useServerState} from '@shopify/hydrogen/client';
/**
* A simple wrapper for Hydrogen's `<Link />` component.
*
* @param {string} props.handle - The handle of the product in Shopify
* @param {string} [props.variantId] - Unencoded variant ID.
*/
const LinkProduct = (props) => {
const {children, className, handle, onClick, variantId} = props;
const {setServerState} = useServerState();
// Return early with children if no valid handle found
if (!handle) {
return children;
}
let productUrl = `/products/${handle}`;
if (variantId) {
productUrl += `?variant=${variantId}`;
}
const handleClick = () => {
if (variantId) {
setServerState('variantId', variantId);
}
if (onClick) {
onClick();
}
};
return (
<Link className={className} onClick={handleClick} to={productUrl}>
{children}
</Link>
);
};
export default LinkProduct;