Implementing Dependent Dropdowns for Address Fields in Shopify Checkout UI Extension

Implementing Dependent Dropdowns for Address Fields in Shopify Checkout UI Extension

Jdobles
Shopify Partner
1 0 0

Hello, Shopify Community!

I am working on customizing the checkout UI for our local website in Costa Rica. As part of our address format, we include Province, Canton (similar to state), and Distrito (similar to city). To make the checkout process smoother for our customers, I am trying to implement dependent dropdowns for these address fields within a Shopify UI extension.

So far, I have managed to create the select components for Canton and Distrito. My current setup allows these fields to be displayed correctly. However, I am encountering difficulties in establishing a dependency where:

  1. The Canton dropdown should dynamically update its options based on the selected Province.
  2. Subsequently, the Distrito dropdown should update its options based on the selected Canton.

I want to ensure that when a user selects a Province, only the relevant Cantons for that Province are displayed, and the same logic applies between Canton and Distrito.

Here’s a snippet of what I've accomplished so far:

 

import {extension, Select} from '@shopify/ui-extensions/checkout';

export default extension('purchase.checkout.actions.render-before', (root) => {
// Initial options for the Cantón select
const cantonOptions = [
{ value: '1', label: 'Cantón 1' },
{ value: '2', label: 'Cantón 2' },
{ value: '3', label: 'Cantón 3' },
{ value: '4', label: 'Cantón 4' },
{ value: '5', label: 'Cantón 5' },

];

// Distrito mapping for each Cantón
const distritoMappings = {
'1': [{ value: '1-1', label: 'Distrito 1-1' }, { value: '1-2', label: 'Distrito 1-2' }],
'2': [{ value: '2-1', label: 'Distrito 2-1' }, { value: '2-2', label: 'Distrito 2-2' }],

};

// Create the Cantón select
const cantonSelect = root.createComponent(Select, {
label: 'Cantón',
value: cantonOptions[0].value,
options: cantonOptions,
onChange: (value) => {
// Update the Distrito select options based on the selected Cantón
distritoSelect.updateProps({ options: distritoMappings[value] || [] });
},
});

// Initially, Distritos will be populated based on the default Cantón selected
const distritoSelect = root.createComponent(Select, {
label: 'Distrito',
options: distritoMappings[cantonOptions[0].value] || [],
});

root.appendChild(cantonSelect);
root.appendChild(distritoSelect);
});
Replies 0 (0)