Skip to main content

Create the UI for a pre-order and Try Before You Buy (TBYB) app

Previously, you set up the foundation of your app. You're now ready to add app components that can help merchants create their pre-orders.

On the app page, you want to add functionality that enables merchants to do the following tasks:

  • Set the pre-order name
  • Configure the delivery, inventory, and billing policies for the pre-order
  • Select products that will have the pre-order

You'll use Polaris and App Bridge to build the user interface. You'll use GraphQL Admin API mutations and queries to create and retrieve pre-orders.

At the end of this tutorial, you'll have an understanding on how to create pre-orders. This app will be simple, but you'll learn where to find resources to build more complex features on your own.

Note

The sample app in this tutorial is assigned with a PRE_ORDER category. When you create your own app, you can assign a category based on the app's purpose. For more information, refer to Selling plans category.


In this tutorial, you'll learn how to do the following tasks:

  • Add new routes to your app's server that call the Shopify Admin API
  • Add UI to create a pre-order
  • Test your app on a dev store

This tutorial is not intended to give you a full example on how to build a pre-order application, but more a reference starter.



Anchor to Step 1: Create the pre-order creation routeStep 1: Create the pre-order creation route

Create a file app.create.jsx under app/routes. This file creates the /app/create route, where merchants create a pre-order.

In the following steps, you add components and an action to this file. For the complete code, refer to Step 4: Complete create page.


Anchor to Step 2: Create app componentsStep 2: Create app components

Create the following app components:

Tip

We recommend keeping your app component files in the app/components folder.

Anchor to Create the name componentCreate the name component

Create a component that enables merchants to set the pre-order name. The name component includes the following Polaris components:

A screen capture showing the name component

In your app/routes/app.create.jsx file, add the following code:

app/routes/app.create.jsx

import { useState } from "react";

export default function Index() {
const [sellingPlanName, setSellingPlanName] = useState("");

const handleSellingPlanNameChange = (newValue) => {
setSellingPlanName(newValue);
};

return (
<s-page heading="Create a pre-order">
<s-section heading="Pre-order details">
<s-text-field
label="Pre-order name"
name="sellingPlanName"
value={sellingPlanName}
onChange={(e) => handleSellingPlanNameChange(e.target.value)}
required
/>
</s-section>
</s-page>
);
}

Anchor to Create the checkout charge componentCreate the checkout charge component

When merchants create a pre-order, they can decide the initial charge when customers check out. The type of charge can be set with a PERCENTAGE or PRICE type. Learn more about selling plan checkout charge types and selling plan checkout charge values.

The checkout charge component includes the following Polaris components:

The date picker stores the selected date as a YYYY-MM-DD string. Because the date picker doesn't have a label property, the component nests it in a section. The section's heading describes the date that the merchant selects.

A screen capture showing the deposit component

In the app/components folder, create the file CheckoutCharge.jsx.

app/components/CheckoutCharge.jsx

export default function CheckoutCharge({
selectedDate,
setSelectedDate,
initialCheckoutCharge,
setInitialCheckoutCharge,
isLoading,
}) {
return (
<s-stack gap="base">
<s-number-field
label="Initial deposit"
name="checkoutCharge"
suffix="%"
value={initialCheckoutCharge}
onChange={(e) => setInitialCheckoutCharge(e.target.value)}
min="0"
max="100"
disabled={isLoading || undefined}
required
/>
{initialCheckoutCharge < 100 && (
<s-section heading="Remaining balance charge date">
<s-date-picker
type="single"
name="selectedDate"
value={selectedDate}
onChange={(event) => setSelectedDate(event.currentTarget.value)}
/>
</s-section>
)}
</s-stack>
);
}

Anchor to Create the product picker componentCreate the product picker component

Create a component that enables merchants to select the products for the pre-order. The product selection component uses the Resource Picker API. When a merchant enters a search term and clicks Browse, the component passes the search term to the resource picker as the query option.

A screen capture showing the product selection component

In the app/components folder, create the file ProductPicker.jsx.

app/components/ProductPicker.jsx

import { useState } from "react";

export default function ProductPicker({
selectedProducts,
setSelectedProducts,
isLoading,
}) {
const [searchTerm, setSearchTerm] = useState("");

async function selectProducts(selectedProductIds, searchQuery) {
const selectedItems = await window.shopify.resourcePicker({
selectionIds: selectedProductIds,
multiple: true,
query: searchQuery,
type: "product",
action: "select",
});

if (selectedItems) {
setSelectedProducts(selectedItems);
}
}

return (
<s-stack gap="base">
<s-grid gridTemplateColumns="1fr auto" gap="base" alignItems="start">
<s-search-field
id="productSearch"
name="productSearch"
placeholder="Search products"
value={searchTerm}
onInput={(event) => setSearchTerm(event.currentTarget.value)}
disabled={isLoading || undefined}
/>
<s-button
onClick={() => selectProducts([], searchTerm)}
disabled={isLoading || undefined}
>
Browse
</s-button>
</s-grid>

{selectedProducts && selectedProducts.length > 0 && (
<s-stack gap="base">
{selectedProducts.map(
({ id, images, variants, title, totalVariants }, index) => {
const hasImage = images && images.length;

return (
<s-grid
key={`${id}-${index}`}
gridTemplateColumns="auto 1fr auto"
gap="base"
alignItems="center"
>
<s-thumbnail
src={hasImage ? images[0].originalSrc : undefined}
alt={
hasImage && images[0].altText ? images[0].altText : ""
}
size="base"
/>
<s-stack>
<s-text>{title}</s-text>
{totalVariants !== undefined ? (
<s-text color="subdued">
({variants?.length || totalVariants} of{" "}
{totalVariants} variants selected)
</s-text>
) : null}
</s-stack>
<s-link onClick={() => selectProducts(selectedProducts)}>
Edit
</s-link>
</s-grid>
);
},
)}
</s-stack>
)}
</s-stack>
);
}

Anchor to Step 3: Action to create the pre-orderStep 3: Action to create the pre-order

The next step is to create the action that will make it possible to create the pre-order with all the information we are gathering with the previous created components. Add the action inside your app/routes/app.create.jsx file. The following action is currently showing a working example on how to use the sellingPlanGroupCreate mutation to create a pre-order, this example can also be updated to create a Try before you buy.

app/routes/app.create.jsx

export const action = async ({ request }) => {
const { admin } = await authenticate.admin(request);
const form = await request.formData();
const sellingPlanName = form.get("sellingPlanName");
const initialCheckoutCharge = form.get("initialCheckoutCharge");
const selectedProducts = form.get("selectedProducts");
const selectedProductsArray = selectedProducts
? selectedProducts.split(",")
: [];
const remainingBalanceChargeTime = form.get("remainingBalanceChargeTime");
const haveRemainingBalance = Number(initialCheckoutCharge) < 100;
const response = await admin.graphql(
`#graphql
mutation sellingPlanGroupCreate($input: SellingPlanGroupInput!, $resources: SellingPlanGroupResourceInput!) {
sellingPlanGroupCreate(input: $input, resources: $resources) {
sellingPlanGroup {
id
}
userErrors {
field
message
}
}
}`,
{
variables: {
input: {
name: sellingPlanName,
merchantCode: "Pre-order",
options: ["pre-order"],
position: 1,
sellingPlansToCreate: [
{
name: "Pre-order with deposit",
options: "Pre-order with deposit",
category: "PRE_ORDER",
billingPolicy: {
fixed: {
checkoutCharge: {
type: "PERCENTAGE",
value: {
percentage: Number(initialCheckoutCharge),
},
},
remainingBalanceChargeTrigger: haveRemainingBalance
? "EXACT_TIME"
: "NO_REMAINING_BALANCE",
remainingBalanceChargeExactTime: haveRemainingBalance
? new Date(remainingBalanceChargeTime).toISOString()
: null,
},
},
deliveryPolicy: {
fixed: {
fulfillmentTrigger: "UNKNOWN",
},
},
inventoryPolicy: {
reserve: "ON_FULFILLMENT",
},
},
],
},
resources: {
productIds: selectedProductsArray,
},
},
},
);
const responseJson = await response.json();

const userErrors = responseJson.data?.sellingPlanGroupCreate?.userErrors;
if (userErrors && userErrors.length > 0) {
return {
errors: userErrors.map(error => error.message).join(', ')
};
}

return {
sellingPlanGroup:
responseJson.data?.sellingPlanGroupCreate?.sellingPlanGroup?.id,
};
};

Anchor to Step 4: Complete create pageStep 4: Complete create page

The following example shows the complete code for the app/routes/app.create.jsx file. We use the Toast API to add feedback when a merchant is creating a new pre-order.

The date picker starts with no date selected. If the initial deposit is less than 100% and the merchant hasn't selected a date, then handleSubmit shows an error toast. The createPreorder function converts the selected date to the start of that day in the time zone of the merchant's browser. The action passes that time to the sellingPlanGroupCreate mutation as remainingBalanceChargeExactTime.

app/routes/app.create.jsx

import { useState, useEffect } from "react";
import { useActionData, useNavigation, useSubmit } from "react-router";
import { authenticate } from "../shopify.server";
import ProductPicker from "../components/ProductPicker";
import CheckoutCharge from "../components/CheckoutCharge";
import { boundary } from "@shopify/shopify-app-react-router/server";

export const action = async ({ request }) => {
const { admin } = await authenticate.admin(request);
const form = await request.formData();
const sellingPlanName = form.get("sellingPlanName");
const initialCheckoutCharge = form.get("initialCheckoutCharge");
const selectedProducts = form.get("selectedProducts");
const selectedProductsArray = selectedProducts
? selectedProducts.split(",")
: [];
const remainingBalanceChargeTime = form.get("remainingBalanceChargeTime");
const haveRemainingBalance = Number(initialCheckoutCharge) < 100;
const response = await admin.graphql(
`#graphql
mutation sellingPlanGroupCreate($input: SellingPlanGroupInput!, $resources: SellingPlanGroupResourceInput!) {
sellingPlanGroupCreate(input: $input, resources: $resources) {
sellingPlanGroup {
id
}
userErrors {
field
message
}
}
}`,
{
variables: {
input: {
name: sellingPlanName,
merchantCode: "Pre-order",
options: ["pre-order"],
position: 1,
sellingPlansToCreate: [
{
name: "Pre-order with deposit",
options: "Pre-order with deposit",
category: "PRE_ORDER",
billingPolicy: {
fixed: {
checkoutCharge: {
type: "PERCENTAGE",
value: {
percentage: Number(initialCheckoutCharge),
},
},
remainingBalanceChargeTrigger: haveRemainingBalance
? "EXACT_TIME"
: "NO_REMAINING_BALANCE",
remainingBalanceChargeExactTime: haveRemainingBalance
? new Date(remainingBalanceChargeTime).toISOString()
: null,
},
},
deliveryPolicy: {
fixed: {
fulfillmentTrigger: "UNKNOWN",
},
},
inventoryPolicy: {
reserve: "ON_FULFILLMENT",
},
},
],
},
resources: {
productIds: selectedProductsArray,
},
},
},
);
const responseJson = await response.json();

const userErrors = responseJson.data?.sellingPlanGroupCreate?.userErrors;
if (userErrors && userErrors.length > 0) {
return {
errors: userErrors.map(error => error.message).join(', ')
};
}

return {
sellingPlanGroup:
responseJson.data?.sellingPlanGroupCreate?.sellingPlanGroup?.id,
};
};

export default function Index() {
const nav = useNavigation();
const actionData = useActionData();
const submit = useSubmit();
const [selectedProducts, setSelectedProducts] = useState([]);
const [sellingPlanName, setSellingPlanName] = useState("");
const [initialCheckoutCharge, setInitialCheckoutCharge] = useState(0);
const [errors, setErrors] = useState(null);

const handleSellingPlanNameChange = (newValue) => {
setSellingPlanName(newValue);
};

const isLoading =
["loading", "submitting"].includes(nav.state) && nav.formMethod === "POST";

useEffect(() => {
if (actionData?.sellingPlanGroup) {
shopify.toast.show("Pre-order created", {
isError: false,
});
} else if (actionData?.errors) {
setErrors(actionData.errors);
}
}, [actionData]);

const [selectedDate, setSelectedDate] = useState("");

const createPreorder = () =>
submit(
{
selectedProducts: selectedProducts.map((product) => product.id),
sellingPlanName,
initialCheckoutCharge,
remainingBalanceChargeTime:
initialCheckoutCharge < 100
? new Date(`${selectedDate}T00:00:00`).toISOString()
: null,
},
{ replace: true, method: "POST" },
);

const handleSubmit = (event) => {
event.preventDefault();

// Clear any existing errors
setErrors(null);

// Validate required fields
if (!sellingPlanName.trim()) {
shopify.toast.show("Please enter a pre-order name", {
isError: true,
});
return;
}

if (selectedProducts.length === 0) {
shopify.toast.show("Please select at least one product", {
isError: true,
});
return;
}

if (initialCheckoutCharge < 0 || initialCheckoutCharge > 100) {
shopify.toast.show("Initial deposit must be between 0% and 100%", {
isError: true,
});
return;
}

if (initialCheckoutCharge < 100 && !selectedDate) {
shopify.toast.show("Please select a remaining balance charge date", {
isError: true,
});
return;
}

createPreorder();
};

const handleReset = () => {
setSelectedProducts([]);
setSellingPlanName("");
setInitialCheckoutCharge(0);
setSelectedDate("");
setErrors(null);
};

return (
<form data-save-bar onSubmit={handleSubmit} onReset={handleReset}>
<s-page heading="Create a pre-order">
<s-link slot="breadcrumb-actions" href="/app">
Pre-orders
</s-link>
{errors && (
<s-banner tone="critical" heading="There was an error creating the pre-order">
<s-text>{errors}</s-text>
</s-banner>
)}
<s-stack gap="base">
<s-section heading="Pre-order details">
<s-text-field
label="Pre-order name"
name="sellingPlanName"
value={sellingPlanName}
onChange={(e) => handleSellingPlanNameChange(e.target.value)}
disabled={isLoading || undefined}
required
/>
</s-section>

<s-section heading="Payment settings">
<CheckoutCharge
selectedDate={selectedDate}
setSelectedDate={setSelectedDate}
initialCheckoutCharge={initialCheckoutCharge}
setInitialCheckoutCharge={setInitialCheckoutCharge}
isLoading={isLoading}
/>
</s-section>

<s-section heading="Products">
<ProductPicker
selectedProducts={selectedProducts}
setSelectedProducts={setSelectedProducts}
isLoading={isLoading}
/>
</s-section>
</s-stack>
</s-page>
</form>
);
}

export const headers = (headersArgs) => {
return boundary.headers(headersArgs);
};

The code that you just created is only a first step to create a complete pre-order or Try before you buy app. You can use the following API object to improve your application:


Was this page helpful?