Create a country selector
In this guide you will learn how to create a country selector so that buyers can change the store language and currency.
Requirements
Anchor link to section titled "Requirements"- You've completed the Hydrogen getting started with a
Hello World
example project. - You've setup the regions and languages for your store with Shopify Markets.
- You've completed the setup multi-region and multilingual storefront with URL paths or setup multi-region and multilingual storefront with domains and subdomains tutorial.
- You're familiar with using the Storefront API with Shopify Markets.
Step 1: Provide a list of available countries
Anchor link to section titled "Step 1: Provide a list of available countries"Create a JSON file with a list of available countries that will be rendered at every page. You can use the /app/data/countries.js
file in the Hydrogen demo store as a point of reference.
For performance and SEO reasons, Shopify recommends using a static JSON variable for the countries. Optionally, you can create a build script that generates this file on build.
The following is an example of the countries data structure:
Step 2: Create getLocaleFromRequest utility
Anchor link to section titled "Step 2: Create getLocaleFromRequest utility"Create the getLocaleFromRequest
utility function. This function will read the request and determine the locale to be used throughout the app.
You can use the /app/lib/utils.js
file in the demo Hydrogen demo store as an example.
Step 3: Add the selected locale in the root
loader function
Anchor link to section titled "Step 3: Add the selected locale in the root loader function"This step gets the user's request and finds the associated locale. You should make the selected locale available throughout the app with the loader
.
Step 4: Create a resource route for the available countries
Anchor link to section titled "Step 4: Create a resource route for the available countries"A Remix resource route is useful when the UI fetches the available countries to display.
You can use the /routes/($locale).api.countries.js
in the The Hydrogen demo store as an example.
Step 5: Render the available countries as a form
Anchor link to section titled "Step 5: Render the available countries as a form"Create a CountrySelector
component using Remix Forms:
You can use the app/components/CountrySelector.js
file in the the Hydrogen demo store as an example.
Step 6: Handle form submit
Anchor link to section titled "Step 6: Handle form submit"Create the /app/routes/($locale).jsx
route that will handle the form submit action
Step 7: Make sure re-rendering happens at the root HTML
Anchor link to section titled "Step 7: Make sure re-rendering happens at the root HTML"Make sure to provide a key
to the components that will change due to localization.
Specially for URL path localization schemes.
Sometimes, React won't know when to re-render a component. To avoid this problem, add localization as key in the App
.