Add collection handle to product URL

Applicable only for Shopify

🚧

This functionality is only available for Shopify users.

📘

Components:

If you want to add a collection handle to your product URL, e.g. if you have a collection: /collection/shorts and a product URL: /product/nice-shorts and you want to have collection breadcrumbs in the product page like this: /collection/shorts/products/nice-shorts.

To do that, you would need to update a few things as shown below:

/* some imports here */
import { withProps, compose, withHandlers } from 'recompose';

/* some code here */

/* we need this function to navigate to a different url */
const navigate = (openInNewWindow, url) => {
  if (!window) return;
  if (openInNewWindow) return window.open(url, '_blank');
  return window.location.href = url;
}

/* this function updates the url by adding collection handle */
const appendCollectionSlot = (url) =>{
  const collectionSlot = findify.utils.collectionPath();
  return url.split('/products/').join(`/${collectionSlot}/products/`);
}

/* this enhancer has a check for whether it's a collection or not and creates a new onClick function when clicked on a product card to change the default onClick event */
const enhancer = compose(
  withProps(({ config }) => ({
    isCollection: config.get('type') === 'smart-collection',
  })),
  withHandlers({
    onClick: ({ item, isCollection }) => (e) =>{
      e.preventDefault();
      const openInNewWindow = e && (e.ctrlKey || e.metaKey);
      const productUrl = isCollection ? appendCollectionSlot(item.get('product_url')) : item.get('product_url');
      item.analytics.sendEvent(
        'click-item',
        { rid: item.meta.get('rid'), item_id: item.get('id') },
        !openInNewWindow
      );
      navigate(openInNewWindow, productUrl);
    }
  })
);

/* some code here */

const ProductCardView: React.SFC<IProductCardProps> = ({
  item,
  config,
  theme,
  isCollection,
  onClick // new onClick function
}: any) => (
  <a
    onClick={onClick} // place this new onClick function here
    href={item.get('product_url')}
    className={classNames(
      theme.root,
      config.get('simple') && theme.simple,
      theme.productCard,
    )}
  >
    // some code
  </a>
)

export default enhancer(ProductCardView); // add the enhancer