Create String for Snipcart product options

Originally published on 22 February, 2021 by Jacob Stordahl

If you're working with Snipcart and want to sell products with variations, you'll need to create a string that follows this format based on the variations...

variantName[priceChange] | variantName[priceChange] | etc

eg. S[+-1]|M[+0]|L[+1]|XL[+-1]

To create this string dynamically, we'll use this function...

createString = (values) => {
  return values.map( option => {
    const price = option.price >= 0 ? `[+${option.price - this.state.selected.price}]` : `[${option.price}]`;
     return `${option.title}${price}`;
  }).join('|');
}

This function createString() accepts an array of objects we're calling values. Each object in this array must contain a price value & title value. This function is dependent on a state variable called selected which should be initialized with the first object in the array we pass to createString(). If you're using the Sanity default e-commerce schema, the variants array fits these conditions out of the box!

© 2021 Jacob Stordahl | built with Steel