Raw
1 ---
2 tags:
3 - storefront
4 - cart
5 - product
6 - payment
7 - fulfillment
8 - order
9 - region
10 - example
11 products:
12 - cart
13 - product
14 - payment
15 - fulfillment
16 - order
17 - region
18 ---
19
20 import { Card, Prerequisites, Details, CodeTabs, CodeTab } from "docs-ui"
21 import { Github } from "@medusajs/icons"
22
23 export const metadata = {
24 title: `Implement Mobile App with React Native, Expo, and Medusa`,
25 }
26
27 # {metadata.title}
28
29 In this tutorial, you'll learn how to create a mobile app that connects to your Medusa backend with React Native and Expo. You can then publish your app to the Apple App Store and Google Play Store.
30
31 When you install a Medusa application, you get a fully-fledged commerce server and an admin dashboard to manage the commerce store's data. Medusa's [architecture](!docs!/learn/introduction/architecture) is flexible and customizable, allowing you to build your own custom storefronts using any technology you prefer.
32
33 [React Native](https://reactnative.dev/) allows developers to build native apps using React. [Expo](https://expo.dev/) is a platform for universal React applications that makes it easy to build, deploy, and iterate on native iOS and Android apps.
34
35 ## Summary
36
37 By following this tutorial, you'll learn how to:
38
39 1. Set up a Medusa application.
40 2. Create an app with React Native and Expo.
41 3. Connect the Expo app to the Medusa backend.
42 4. Implement essential ecommerce features such as product listing, cart management, and checkout.
43
44 You can follow this guide whether you're new to Medusa or an advanced Medusa developer. However, this tutorial assumes you have a basic understanding of React Native and JavaScript.
45
46 ![Screenshot of home screen of the Expo app](https://res.cloudinary.com/dza7lstvk/image/upload/v1762333811/Medusa%20Resources/CleanShot_2025-11-05_at_11.09.27_lxl2tw.png)
47
48 <Card
49 title="Full Code"
50 text="Find the full code for this tutorial in this repository."
51 href="https://github.com/medusajs/examples/tree/main/react-native-expo"
52 icon={Github}
53 />
54
55 ---
56
57 ## Step 1: Install a Medusa Application
58
59 <Prerequisites items={[
60 {
61 text: "Node.js v20.19.0+ or v22.12.0+",
62 link: "https://nodejs.org/en/download"
63 },
64 {
65 text: "Git CLI tool",
66 link: "https://git-scm.com/downloads"
67 },
68 {
69 text: "PostgreSQL",
70 link: "https://www.postgresql.org/download/"
71 }
72 ]} />
73
74 Start by installing the Medusa application on your machine with the following command:
75
76 ```bash npx2yarnExec
77 npx create-medusa-app@latest
78 ```
79
80 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `N` for no. You'll create the Expo app instead.
81
82 Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name. Once the installation finishes successfully, the Medusa Admin dashboard will open in your browser at `http://localhost:9000/app` with a form to create a new user. Enter the user's credentials and submit the form.
83
84 Then, you can log in with the new user and explore the dashboard.
85
86 <Note title="Ran into Errors?">
87
88 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
89
90 </Note>
91
92 ---
93
94 ## Step 2: Create an Expo App
95
96 In this step, you'll create a new Expo app with React Native.
97
98 In a directory separate from your Medusa application, run the following command to create a new Expo project:
99
100 ```bash npx2yarnExec
101 npx create-expo-app@latest
102 ```
103
104 When prompted, enter a name for your project and wait for the installation to complete.
105
106 Once the installation is complete, navigate to the project directory:
107
108 ```bash
109 cd your-project-name
110 ```
111
112 The rest of this tutorial assumes you're in the Expo app's root directory.
113
114 ---
115
116 ## Step 3: Install Dependencies
117
118 In this step, you'll install dependencies that you'll use while building the Expo app.
119
120 Run the following command to install the required packages:
121
122 ```bash npm2yarn
123 npm install @medusajs/js-sdk @medusajs/types @react-native-async-storage/async-storage @react-native-picker/picker @react-navigation/drawer
124 ```
125
126 You install the following packages:
127
128 - `@medusajs/js-sdk`: Medusa's [JS SDK](../../../js-sdk/page.mdx) to interact with the Medusa backend.
129 - `@medusajs/types`: TypeScript types for Medusa, which are useful when working with Medusa's JS SDK.
130 - `@react-native-async-storage/async-storage`: An asynchronous key-value storage system for React Native, used to store data like cart ID.
131 - `@react-native-picker/picker`: A cross-platform picker component for React Native, used for selecting options like country.
132 - `@react-navigation/drawer`: A navigation library for React Native that provides a drawer-based navigation experience.
133
134 You'll use these packages in the upcoming steps to build the app's functionality.
135
136 ---
137
138 ## Step 4: Update App Theme (Optional)
139
140 In this step, you'll update the theme for the app to ensure a consistent look and feel across all screens. This is optional, and you can customize the theme based on your brand identity instead.
141
142 In your React Native project, you should have the following directories:
143
144 - `constants`: This directory will contain constant values used throughout the app. It should already have a `theme.ts` file.
145 - `hooks`: This directory will contain custom React hooks. It should already have hooks for color schemes: `use-color-scheme.ts`, `use-color-scheme.web.ts`, and `use-theme-color.ts`.
146
147 To update the app's theme, replace the content of the `constants/theme.ts` file with the following:
148
149 ```ts title="constants/theme.ts"
150 /**
151 * Below are the colors that are used in the app. The colors are defined in the light and dark mode.
152 * There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
153 */
154
155 import { Platform } from "react-native"
156
157 const tintColorLight = "#000"
158 const tintColorDark = "#fff"
159
160 export const Colors = {
161 light: {
162 text: "#11181C",
163 background: "#fff",
164 tint: tintColorLight,
165 icon: "#687076",
166 tabIconDefault: "#687076",
167 tabIconSelected: tintColorLight,
168 border: "#e0e0e0",
169 cardBackground: "#f9f9f9",
170 error: "#ff3b30",
171 warning: "#ff9500",
172 success: "#4CAF50",
173 imagePlaceholder: "#f0f0f0",
174 },
175 dark: {
176 text: "#ECEDEE",
177 background: "#151718",
178 tint: tintColorDark,
179 icon: "#9BA1A6",
180 tabIconDefault: "#9BA1A6",
181 tabIconSelected: tintColorDark,
182 border: "#333",
183 cardBackground: "#1a1a1a",
184 error: "#ff3b30",
185 warning: "#ff9500",
186 success: "#4CAF50",
187 imagePlaceholder: "#2a2a2a",
188 },
189 }
190
191 export const Fonts = Platform.select({
192 ios: {
193 /** iOS `UIFontDescriptorSystemDesignDefault` */
194 sans: "system-ui",
195 /** iOS `UIFontDescriptorSystemDesignSerif` */
196 serif: "ui-serif",
197 /** iOS `UIFontDescriptorSystemDesignRounded` */
198 rounded: "ui-rounded",
199 /** iOS `UIFontDescriptorSystemDesignMonospaced` */
200 mono: "ui-monospace",
201 },
202 default: {
203 sans: "normal",
204 serif: "serif",
205 rounded: "normal",
206 mono: "monospace",
207 },
208 web: {
209 sans: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
210 serif: "Georgia, 'Times New Roman', serif",
211 rounded: "'SF Pro Rounded', 'Hiragino Maru Gothic ProN', Meiryo, 'MS PGothic', sans-serif",
212 mono: "SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
213 },
214 })
215 ```
216
217 ---
218
219 ## Step 5: Initialize Medusa JS SDK
220
221 In this step, you'll set up Medusa's [JS SDK](../../../js-sdk/page.mdx) in your Expo app. You'll use the SDK to interact with the Medusa backend.
222
223 To initialize the SDK, create the file `lib/sdk.ts` in your Expo project with the following content:
224
225 ```ts title="lib/sdk.ts"
226 import Medusa from "@medusajs/js-sdk"
227 import AsyncStorage from "@react-native-async-storage/async-storage"
228 import Constants from "expo-constants"
229
230 const MEDUSA_BACKEND_URL =
231 Constants.expoConfig?.extra?.EXPO_PUBLIC_MEDUSA_URL ||
232 process.env.EXPO_PUBLIC_MEDUSA_URL ||
233 "http://localhost:9000"
234
235 const MEDUSA_PUBLISHABLE_API_KEY =
236 Constants.expoConfig?.extra?.EXPO_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY ||
237 process.env.EXPO_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY ||
238 ""
239
240 export const sdk = new Medusa({
241 baseUrl: MEDUSA_BACKEND_URL,
242 debug: __DEV__,
243 auth: {
244 type: "jwt",
245 jwtTokenStorageMethod: "custom",
246 storage: AsyncStorage,
247 },
248 publishableKey: MEDUSA_PUBLISHABLE_API_KEY,
249 })
250 ```
251
252 You configure the SDK with the:
253
254 - Medusa backend URL, which is read from the environment variable `EXPO_PUBLIC_MEDUSA_URL`. If the variable is not set, it defaults to `http://localhost:9000`.
255 - [Publishable API key](../../publishable-api-keys/page.mdx), which is required to retrieve products in the associated sales channel. It is read from the environment variable `EXPO_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY`.
256
257 You also customize the JWT token storage method of the JS SDK to use `AsyncStorage`, which is suitable for React Native apps.
258
259 <Note>
260
261 Refer to the [JS SDK documentation](../../../js-sdk/page.mdx) for more configuration options.
262
263 </Note>
264
265 ### Set Environment Variables
266
267 Next, you'll set the environment variables in your Expo project. Before you do that, you need to retrieve the Medusa backend URL and the Publishable API key.
268
269 The Medusa backend URL is the URL where your Medusa server is running. If you're running the Medusa server locally, it should be the IP address of your machine at the port `9000`. For example, `http://192.168.1.100:9000`.
270
271 You can find your machine's local IP address by running the following command in your terminal:
272
273 <CodeTabs group="os">
274 <CodeTab label="macOS" value="macos">
275
276 ```bash
277 ipconfig getifaddr en0
278 ```
279
280 </CodeTab>
281 <CodeTab label="Linux" value="linux">
282
283 ```bash
284 ip addr
285 ```
286
287 </CodeTab>
288 <CodeTab label="Windows" value="windows">
289
290 ```bash
291 ipconfig
292 ```
293
294 </CodeTab>
295 </CodeTabs>
296
297 Next, to get the Publishable API key, start the Medusa application by running the following command in its directory:
298
299 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
300 npm run dev
301 ```
302
303 Then:
304
305 1. Open the Medusa Admin dashboard at `http://localhost:9000/app` and log in.
306 2. Go to **Settings** > **Publishable API Keys**.
307 3. Either copy the key of an existing Publishable API key, or create a new one by clicking on the **Create Publishable API Key** button.
308
309 Once you have the Medusa backend URL and the Publishable API key, create the file `.env` in the root directory of your Expo project with the following content:
310
311 ```shell title=".env"
312 EXPO_PUBLIC_MEDUSA_URL=http://192.168.1.100:9000
313 EXPO_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY=your_publishable_api_key
314 ```
315
316 Make sure to replace the values with your actual Medusa backend URL and Publishable API key.
317
318 ### Optional: Update CORS in Medusa
319
320 If you plan to test the Expo app in a web browser, you'll need to update the CORS settings in the Medusa backend to allow requests from the Expo development server.
321
322 In your Medusa application's directory, add the Expo development server URL to the `STORE_CORS` and `AUTH_CORS` environment variables in the `.env` file:
323
324 ```env
325 STORE_CORS=previous_values...,http://localhost:8081
326 AUTH_CORS=previous_values...,http://localhost:8081
327 ```
328
329 Append `,http://localhost:8081` to the existing values of `STORE_CORS` and `AUTH_CORS`, which is the default URL for the Expo development server.
330
331 Make sure to restart the Medusa server after making changes to the `.env` file.
332
333 ---
334
335 ## Step 6: Create Region Selector
336
337 In this step, you'll create a region selector component that allows users to select their country and currency. This is important for providing a localized shopping experience.
338
339 To implement this, you'll:
340
341 1. Create a region context to manage the selected region state.
342 2. Create a region selector component that allows users to choose their country and currency from a list.
343 3. Update the app's navigation to add a drawer menu for the region selector.
344
345 ### Create Region Context
346
347 The region context will manage the selected region state and provide it to child components. You'll create a context, a provider component, and a custom hook to access the context.
348
349 To create the region context, create the file `context/region-context.tsx` with the following content:
350
351 export const regionContextHighlights = [
352 ["7", "regions", "Available regions from the Medusa backend."],
353 ["8", "selectedRegion", "The currently selected region."],
354 ["9", "selectedCountryCode", "The selected country code within the selected region."],
355 ["10", "setSelectedRegion", "Update the selected region and country code."],
356 ["11", "loading", "Whether the regions are being loaded."],
357 ["12", "error", "An error message if loading the regions fails."]
358 ]
359
360 ```tsx title="context/region-context.tsx" highlights={regionContextHighlights}
361 import { sdk } from "@/lib/sdk"
362 import type { HttpTypes } from "@medusajs/types"
363 import AsyncStorage from "@react-native-async-storage/async-storage"
364 import React, { createContext, ReactNode, useContext, useEffect, useState } from "react"
365
366 interface RegionContextType {
367 regions: HttpTypes.StoreRegion[];
368 selectedRegion: HttpTypes.StoreRegion | null;
369 selectedCountryCode: string | null;
370 setSelectedRegion: (region: HttpTypes.StoreRegion, countryCode: string) => void;
371 loading: boolean;
372 error: string | null;
373 }
374
375 const RegionContext = createContext<RegionContextType | undefined>(undefined)
376
377 const REGION_STORAGE_KEY = "selected_region_id"
378 const COUNTRY_STORAGE_KEY = "selected_country_code"
379
380 export function RegionProvider({ children }: { children: ReactNode }) {
381 const [regions, setRegions] = useState<HttpTypes.StoreRegion[]>([])
382 const [selectedRegion, setSelectedRegionState] = useState<HttpTypes.StoreRegion | null>(null)
383 const [selectedCountryCode, setSelectedCountryCode] = useState<string | null>(null)
384 const [loading, setLoading] = useState(true)
385 const [error, setError] = useState<string | null>(null)
386
387 // TODO load and select regions
388 }
389
390 // TODO add useRegion hook
391 ```
392
393 You define the `RegionContext` with the following properties that child components can use:
394
395 1. `regions`: An array of available regions fetched from the Medusa backend.
396 2. `selectedRegion`: The currently selected region.
397 3. `selectedCountryCode`: The country code of the selected country within the selected region. This is useful as regions can have multiple countries, and you'll allow customers to select their country.
398 4. `setSelectedRegion`: A function to update the selected region and country code.
399 5. `loading`: A boolean indicating whether the regions are being loaded.
400 6. `error`: An error message if loading the regions fails.
401
402 You also define the `RegionProvider` component that will wrap the app and provide the region context to its children.
403
404 Next, you'll implement the logic to load the regions from the Medusa backend, and manage the selected region state.
405
406 Replace the `// TODO load and select regions` comment with the following:
407
408 export const regionLoadingHighlights = [
409 ["1", "loadRegions", "Load regions from the Medusa backend."],
410 ["41", "useEffect", "Load regions when the component mounts."],
411 ["45", "setSelectedRegion", "Update the selected region and country code."]
412 ]
413
414 ```tsx title="context/region-context.tsx" highlights={regionLoadingHighlights}
415 const loadRegions = async () => {
416 try {
417 setLoading(true)
418 setError(null)
419
420 const { regions: fetchedRegions } = await sdk.store.region.list()
421 setRegions(fetchedRegions)
422
423 // Load saved region and country or use first region's first country
424 const savedRegionId = await AsyncStorage.getItem(REGION_STORAGE_KEY)
425 const savedCountryCode = await AsyncStorage.getItem(COUNTRY_STORAGE_KEY)
426
427 const regionToSelect = savedRegionId
428 ? fetchedRegions.find((r) => r.id === savedRegionId) || fetchedRegions[0]
429 : fetchedRegions[0]
430
431 if (regionToSelect) {
432 setSelectedRegionState(regionToSelect)
433 await AsyncStorage.setItem(REGION_STORAGE_KEY, regionToSelect.id)
434
435 // Set country code - use saved one if it exists in the region, otherwise use first country
436 const countryCodeToSelect = savedCountryCode &&
437 regionToSelect.countries?.some((c) => (c.iso_2 || c.id) === savedCountryCode)
438 ? savedCountryCode
439 : regionToSelect.countries?.[0]?.iso_2 || regionToSelect.countries?.[0]?.id || null
440
441 setSelectedCountryCode(countryCodeToSelect)
442 if (countryCodeToSelect) {
443 await AsyncStorage.setItem(COUNTRY_STORAGE_KEY, countryCodeToSelect)
444 }
445 }
446 } catch (err) {
447 console.error("Failed to load regions:", err)
448 setError("Failed to load regions. Please try again.")
449 } finally {
450 setLoading(false)
451 }
452 }
453
454 // Load regions on mount
455 useEffect(() => {
456 loadRegions()
457 }, [])
458
459 const setSelectedRegion = async (region: HttpTypes.StoreRegion, countryCode: string) => {
460 setSelectedRegionState(region)
461 setSelectedCountryCode(countryCode)
462 await AsyncStorage.setItem(REGION_STORAGE_KEY, region.id)
463 await AsyncStorage.setItem(COUNTRY_STORAGE_KEY, countryCode)
464 }
465
466 return (
467 <RegionContext.Provider
468 value={{
469 regions,
470 selectedRegion,
471 selectedCountryCode,
472 setSelectedRegion,
473 loading,
474 error,
475 }}
476 >
477 {children}
478 </RegionContext.Provider>
479 )
480 ```
481
482 You define the `loadRegions` function that fetches the regions from the Medusa backend using the JS SDK. It also loads any previously selected region and country from `AsyncStorage`, or defaults to the first region and its first country.
483
484 Then, you run the `loadRegions` function when the component mounts using the `useEffect` hook.
485
486 You also define the `setSelectedRegion` function that updates the selected region and country, and saves them to `AsyncStorage`.
487
488 Then, you provide the context values to child components using the `RegionContext.Provider`.
489
490 Finally, you'll create a custom hook in the same file to access the region context easily. Replace the `// TODO add useRegion hook` comment with the following:
491
492 ```tsx title="context/region-context.tsx"
493 export function useRegion() {
494 const context = useContext(RegionContext)
495 if (!context) {
496 throw new Error("useRegion must be used within a RegionProvider")
497 }
498 return context
499 }
500 ```
501
502 You define the `useRegion` hook that retrieves the context value using `useContext`. It also throws an error if the hook is used by a component that is not wrapped in the `RegionProvider`.
503
504 ### Create Region Selector Component
505
506 Next, you'll create the region selector component that allows users to choose their country and currency.
507
508 To create the region selector component, create the file `components/region-selector.tsx` with the following content:
509
510 ```tsx title="components/region-selector.tsx" collapsibleLines="53-87" expandButtonLabel="Show Styles"
511 import { Colors } from "@/constants/theme"
512 import { useRegion } from "@/context/region-context"
513 import { useColorScheme } from "@/hooks/use-color-scheme"
514 import type { HttpTypes } from "@medusajs/types"
515 import React, { useMemo } from "react"
516 import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native"
517
518 interface RegionSelectorProps {
519 onRegionChange?: () => void;
520 }
521
522 interface CountryWithRegion {
523 countryCode: string;
524 countryName: string;
525 region: HttpTypes.StoreRegion;
526 currencyCode: string;
527 }
528
529 export function RegionSelector({ onRegionChange }: RegionSelectorProps) {
530 const {
531 regions,
532 selectedRegion,
533 selectedCountryCode,
534 setSelectedRegion,
535 } = useRegion()
536 const colorScheme = useColorScheme()
537 const colors = Colors[colorScheme ?? "light"]
538
539 // Flatten countries from all regions
540 const countries = useMemo(() => {
541 const countryList: CountryWithRegion[] = []
542
543 regions.forEach((region) => {
544 if (region.countries) {
545 region.countries.forEach((country) => {
546 countryList.push({
547 countryCode: country.iso_2 || country.id,
548 countryName: country.display_name || country.name || country.iso_2 || country.id,
549 region: region,
550 currencyCode: region.currency_code || "",
551 })
552 })
553 }
554 })
555
556 // Sort alphabetically by country name
557 return countryList.sort((a, b) => a.countryName.localeCompare(b.countryName))
558 }, [regions])
559
560 // TODO handle country selection
561 }
562
563 const styles = StyleSheet.create({
564 container: {
565 flex: 1,
566 padding: 16,
567 },
568 title: {
569 fontSize: 20,
570 fontWeight: "700",
571 marginBottom: 20,
572 },
573 countryItem: {
574 flexDirection: "row",
575 alignItems: "center",
576 justifyContent: "space-between",
577 padding: 16,
578 borderRadius: 8,
579 borderWidth: 1,
580 marginBottom: 8,
581 },
582 countryInfo: {
583 flex: 1,
584 },
585 countryName: {
586 fontSize: 16,
587 marginBottom: 4,
588 },
589 currencyCode: {
590 fontSize: 12,
591 },
592 emptyText: {
593 fontSize: 14,
594 textAlign: "center",
595 marginTop: 20,
596 },
597 })
598 ```
599
600 You define the `RegionSelector` component that receives an optional `onRegionChange` prop. This prop is a callback function that will be called when the user selects a new region.
601
602 In the component, you:
603
604 1. Use the `useRegion` hook to access all regions, the selected region and country, and the function to set the selected region.
605 2. Use the `useColorScheme` hook to get the current color scheme and apply the appropriate colors.
606 3. Create a memoized list of countries by flattening the countries from all regions. Each country includes its associated region and currency code. The list is sorted alphabetically by country name.
607
608 Next, you'll implement the logic to handle country selection and render the list of countries. Replace the `// TODO handle country selection` comment with the following:
609
610 ```tsx title="components/region-selector.tsx"
611 const handleSelectCountry = async (countryWithRegion: CountryWithRegion) => {
612 setSelectedRegion(countryWithRegion.region, countryWithRegion.countryCode)
613 onRegionChange?.()
614 }
615
616 const isCountrySelected = (countryWithRegion: CountryWithRegion) => {
617 return selectedRegion?.id === countryWithRegion.region.id &&
618 selectedCountryCode === countryWithRegion.countryCode
619 }
620
621 return (
622 <ScrollView style={styles.container}>
623 <Text style={[styles.title, { color: colors.text }]}>Select Country</Text>
624 {countries.length === 0 ? (
625 <Text style={[styles.emptyText, { color: colors.icon }]}>
626 No countries available
627 </Text>
628 ) : (
629 countries.map((country) => {
630 const isSelected = isCountrySelected(country)
631
632 return (
633 <TouchableOpacity
634 key={`${country.region.id}-${country.countryCode}`}
635 style={[
636 styles.countryItem,
637 {
638 backgroundColor: isSelected ? colors.tint + "20" : "transparent",
639 borderColor: colors.icon + "30",
640 },
641 ]}
642 onPress={() => handleSelectCountry(country)}
643 >
644 <View style={styles.countryInfo}>
645 <Text
646 style={[
647 styles.countryName,
648 {
649 color: isSelected ? colors.tint : colors.text,
650 fontWeight: isSelected ? "600" : "400",
651 },
652 ]}
653 >
654 {country.countryName}
655 </Text>
656 <Text style={[styles.currencyCode, { color: colors.icon }]}>
657 {country.currencyCode.toUpperCase()}
658 </Text>
659 </View>
660 {isSelected && (
661 <Text style={{ color: colors.tint, fontSize: 18 }}>✓</Text>
662 )}
663 </TouchableOpacity>
664 )
665 })
666 )}
667 </ScrollView>
668 )
669 ```
670
671 You define the `handleSelectCountry` function that is called when a user selects a country. It updates the selected region and country using the `setSelectedRegion` function from the context, and calls the `onRegionChange` callback if provided.
672
673 You also define the `isCountrySelected` function that checks if a given country is currently selected.
674
675 Finally, you render the countries in a scrollable view. For each country, you create a touchable item that displays the country name and currency code. The selected country is highlighted, and a checkmark is shown next to it.
676
677 ### Add Drawer Content Component
678
679 Next, you'll create a custom drawer content component that includes the region selector in the app's navigation drawer.
680
681 Create the file `components/drawer-content.tsx` with the following content:
682
683 ```tsx title="components/drawer-content.tsx"
684 import { DrawerContentComponentProps, DrawerContentScrollView } from "@react-navigation/drawer"
685 import React from "react"
686 import { StyleSheet, View } from "react-native"
687 import { RegionSelector } from "./region-selector"
688
689 export function DrawerContent(props: DrawerContentComponentProps) {
690 return (
691 <DrawerContentScrollView {...props}>
692 <View style={styles.container}>
693 <RegionSelector onRegionChange={() => props.navigation.closeDrawer()} />
694 </View>
695 </DrawerContentScrollView>
696 )
697 }
698
699 const styles = StyleSheet.create({
700 container: {
701 flex: 1,
702 },
703 })
704 ```
705
706 The `DrawerContent` component receives the drawer navigation props. You render the `RegionSelector` component and pass an `onRegionChange` callback that closes the drawer when a region is selected.
707
708 ### Add Drawer Navigation
709
710 Finally, you'll update the app's navigation to wrap the main screens in a drawer navigator that uses the custom drawer content.
711
712 If you have an `app/(tabs)` directory for tab navigation, remove it for now. You'll add it later inside the drawer navigator.
713
714 Then, create the directory `app/(drawer)` which will contain the drawer navigation setup.
715
716 Next, create the file `app/(drawer)/_layout.tsx` with the following content:
717
718 ```tsx title="app/(drawer)/_layout.tsx"
719 import { Drawer } from "expo-router/drawer"
720
721 import { DrawerContent } from "@/components/drawer-content"
722
723 export default function DrawerLayout() {
724 return (
725 <Drawer
726 drawerContent={(props) => <DrawerContent {...props} />}
727 screenOptions={{
728 headerShown: false,
729 drawerPosition: "left",
730 }}
731 >
732 {/* TODO add tabs screens */}
733 </Drawer>
734 )
735 }
736 ```
737
738 The `DrawerLayout` component sets up the drawer navigator using Expo Router's `Drawer` component.
739
740 The custom drawer content is shown on the left side of the screen, and the header is hidden.
741
742 Later, you'll add the tab screens inside the drawer navigator.
743
744 Next, replace the content of the file `app/_layout.tsx` with the following:
745
746 ```tsx title="app/_layout.tsx"
747 import { useColorScheme } from "@/hooks/use-color-scheme"
748 import { DarkTheme, DefaultTheme, ThemeProvider } from "@react-navigation/native"
749 import { Stack } from "expo-router"
750 import { StatusBar } from "expo-status-bar"
751 import { GestureHandlerRootView } from "react-native-gesture-handler"
752 import "react-native-reanimated"
753 import { RegionProvider } from "@/context/region-context"
754
755 export default function RootLayout() {
756 const colorScheme = useColorScheme()
757
758 return (
759 <GestureHandlerRootView style={{ flex: 1 }}>
760 <ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
761 <RegionProvider>
762 <Stack screenOptions={{ headerShown: false }}>
763 <Stack.Screen name="(drawer)" options={{ headerShown: false }} />
764 {/* TODO: Add checkout and order confirmation screens */}
765 </Stack>
766 <StatusBar style="auto" />
767 </RegionProvider>
768 </ThemeProvider>
769 </GestureHandlerRootView>
770 )
771 }
772 ```
773
774 The key changes are:
775
776 1. Wrap the app in the `RegionProvider` to provide the region context to all components.
777 2. Set the initial screen to the `(drawer)` layout, which contains the drawer navigator.
778
779 Later, you'll add the checkout and order confirmation screens to the stack navigator.
780
781 You'll test the region selector after implementing the main screens of the app in the next steps.
782
783 ---
784
785 ## Step 7: Create Cart Context
786
787 In this step, you'll create a cart context to manage the customer's cart state throughout the app. The cart context will allow you to create, manage, and complete the cart.
788
789 ### Create Cart Context
790
791 Create the file `context/cart-context.tsx` with the following content:
792
793 export const cartContextHighlights = [
794 ["9", "cart", "The current cart object."],
795 ["10", "addToCart", "Add an item to the cart."],
796 ["11", "updateItemQuantity", "Update the quantity of an item in the cart."],
797 ["12", "removeItem", "Remove an item from the cart."],
798 ["13", "refreshCart", "Refresh the cart data from the backend."],
799 ["14", "clearCart", "Clear the cart, useful after checkout."],
800 ["15", "loading", "Indicate whether a cart operation is in progress."],
801 ["16", "error", "An error message if a cart operation fails."]
802 ]
803
804 ```tsx title="context/cart-context.tsx" highlights={cartContextHighlights}
805 import { sdk } from "@/lib/sdk"
806 import { FetchError } from "@medusajs/js-sdk"
807 import type { HttpTypes } from "@medusajs/types"
808 import AsyncStorage from "@react-native-async-storage/async-storage"
809 import React, { createContext, ReactNode, useCallback, useContext, useEffect, useState } from "react"
810 import { useRegion } from "./region-context"
811
812 interface CartContextType {
813 cart: HttpTypes.StoreCart | null;
814 addToCart: (variantId: string, quantity: number) => Promise<void>;
815 updateItemQuantity: (itemId: string, quantity: number) => Promise<void>;
816 removeItem: (itemId: string) => Promise<void>;
817 refreshCart: () => Promise<void>;
818 clearCart: () => Promise<void>;
819 loading: boolean;
820 error: string | null;
821 }
822
823 const CartContext = createContext<CartContextType | undefined>(undefined)
824
825 const CART_STORAGE_KEY = "cart_id"
826
827 export function CartProvider({ children }: { children: ReactNode }) {
828 const [cart, setCart] = useState<HttpTypes.StoreCart | null>(null)
829 const [loading, setLoading] = useState(false)
830 const [error, setError] = useState<string | null>(null)
831 const { selectedRegion } = useRegion()
832
833 // TODO load cart
834 }
835
836 // TODO add useCart hook
837 ```
838
839 You define the `CartContext` with the following properties that child components can use:
840
841 - `cart`: The current cart object.
842 - `addToCart`: A function to add an item to the cart.
843 - `updateItemQuantity`: A function to update the quantity of an item in the cart.
844 - `removeItem`: A function to remove an item from the cart.
845 - `refreshCart`: A function to refresh the cart data from the backend.
846 - `clearCart`: A function to clear the cart, which is useful after checkout.
847 - `loading`: A boolean indicating whether a cart operation is in progress.
848 - `error`: An error message if a cart operation fails.
849
850 You also define the `CartProvider` component that will wrap the app and provide the cart context to its children.
851
852 Next, you'll implement the logic to load the cart from the Medusa backend. Replace the `// TODO load cart` comment with the following:
853
854 ```tsx title="context/cart-context.tsx"
855 const loadCart = useCallback(async () => {
856 if (!selectedRegion) {return null}
857
858 try {
859 setLoading(true)
860 setError(null)
861
862 const savedCartId = await AsyncStorage.getItem(CART_STORAGE_KEY)
863
864 if (savedCartId) {
865 try {
866 const { cart: fetchedCart } = await sdk.store.cart.retrieve(savedCartId, {
867 fields: "+items.*",
868 })
869
870 setCart(fetchedCart)
871 return fetchedCart
872 } catch {
873 // Cart not found or invalid, remove from storage
874 await AsyncStorage.removeItem(CART_STORAGE_KEY)
875 }
876 }
877
878 // Create new cart for current region
879 const { cart: newCart } = await sdk.store.cart.create({
880 region_id: selectedRegion.id,
881 }, {
882 fields: "+items.*",
883 })
884 setCart(newCart)
885 await AsyncStorage.setItem(CART_STORAGE_KEY, newCart.id)
886 return newCart
887 } catch (err) {
888 setError(`Failed to load cart: ${err instanceof FetchError ? err.message : String(err)}`)
889 return null
890 } finally {
891 setLoading(false)
892 }
893 }, [selectedRegion])
894
895 // Load cart on mount
896 useEffect(() => {
897 loadCart()
898 }, [loadCart])
899
900 // TODO handle region update
901 ```
902
903 The `loadCart` function creates or retrieves the saved cart from the Medusa backend using the JS SDK. This function runs when the component mounts using the `useEffect` hook.
904
905 Next, you'll implement the logic to handle region updates, as the cart's region must match the selected region.
906
907 Replace the `// TODO handle region update` comment with the following:
908
909 ```tsx title="context/cart-context.tsx"
910 useEffect(() => {
911 const updateCartRegion = async () => {
912 if (!cart || !selectedRegion || cart.region_id === selectedRegion.id) {
913 return
914 }
915
916 try {
917 setLoading(true)
918 const { cart: updatedCart } = await sdk.store.cart.update(cart.id, {
919 region_id: selectedRegion.id,
920 }, {
921 fields: "+items.*",
922 })
923 setCart(updatedCart)
924 } catch (err) {
925 setError(`Failed to update cart region: ${err instanceof FetchError ? err.message : String(err)}`)
926 } finally {
927 setLoading(false)
928 }
929 }
930
931 updateCartRegion()
932 }, [selectedRegion])
933
934 // TODO implement cart operations
935 ```
936
937 You add an effect that runs whenever the selected region changes. If the cart's region doesn't match the selected region, it updates the cart's region using the JS SDK.
938
939 Next, you'll implement the cart operations that you defined in the context type. Replace the `// TODO implement cart operations` comment with the following:
940
941 export const cartOperationsHighlights = [
942 ["1", "addToCart", "Add an item to the cart."],
943 ["28", "updateItemQuantity", "Update the quantity of an item in the cart."],
944 ["52", "removeItem", "Remove an item from the cart."],
945 ["71", "refreshCart", "Refresh the cart data from the backend."],
946 ["84", "clearCart", "Clear the cart, useful after checkout."]
947 ]
948
949 ```tsx title="context/cart-context.tsx" highlights={cartOperationsHighlights}
950 const addToCart = async (variantId: string, quantity: number) => {
951 let currentCart = cart
952
953 if (!currentCart) {
954 currentCart = await loadCart()
955 if (!currentCart) {throw new Error("Could not create cart")}
956 }
957
958 try {
959 setLoading(true)
960 setError(null)
961
962 const { cart: updatedCart } = await sdk.store.cart.createLineItem(currentCart.id, {
963 variant_id: variantId,
964 quantity,
965 }, {
966 fields: "+items.*",
967 })
968 setCart(updatedCart)
969 } catch (err) {
970 setError(`Failed to add item to cart: ${err instanceof FetchError ? err.message : String(err)}`)
971 throw err
972 } finally {
973 setLoading(false)
974 }
975 }
976
977 const updateItemQuantity = async (itemId: string, quantity: number) => {
978 if (!cart) {return}
979
980 try {
981 setLoading(true)
982 setError(null)
983
984 const { cart: updatedCart } = await sdk.store.cart.updateLineItem(
985 cart.id,
986 itemId,
987 { quantity },
988 {
989 fields: "+items.*",
990 }
991 )
992 setCart(updatedCart)
993 } catch (err) {
994 setError(`Failed to update quantity: ${err instanceof FetchError ? err.message : String(err)}`)
995 throw err
996 } finally {
997 setLoading(false)
998 }
999 }
1000
1001 const removeItem = async (itemId: string) => {
1002 if (!cart) {return}
1003
1004 try {
1005 setLoading(true)
1006 setError(null)
1007
1008 const { parent: updatedCart } = await sdk.store.cart.deleteLineItem(cart.id, itemId, {
1009 fields: "+items.*",
1010 })
1011 setCart(updatedCart!)
1012 } catch (err) {
1013 setError(`Failed to remove item: ${err instanceof FetchError ? err.message : String(err)}`)
1014 throw err
1015 } finally {
1016 setLoading(false)
1017 }
1018 }
1019
1020 const refreshCart = async () => {
1021 if (!cart) {return}
1022
1023 try {
1024 const { cart: updatedCart } = await sdk.store.cart.retrieve(cart.id, {
1025 fields: "+items.*",
1026 })
1027 setCart(updatedCart)
1028 } catch (err) {
1029 setError(`Failed to refresh cart: ${err instanceof FetchError ? err.message : String(err)}`)
1030 }
1031 }
1032
1033 const clearCart = async () => {
1034 setCart(null)
1035 await AsyncStorage.removeItem(CART_STORAGE_KEY)
1036 // Create a new cart
1037 if (selectedRegion) {
1038 const { cart: newCart } = await sdk.store.cart.create({
1039 region_id: selectedRegion.id,
1040 }, {
1041 fields: "+items.*",
1042 })
1043 setCart(newCart)
1044 await AsyncStorage.setItem(CART_STORAGE_KEY, newCart.id)
1045 }
1046 }
1047
1048 return (
1049 <CartContext.Provider
1050 value={{
1051 cart,
1052 addToCart,
1053 updateItemQuantity,
1054 removeItem,
1055 refreshCart,
1056 clearCart,
1057 loading,
1058 error,
1059 }}
1060 >
1061 {children}
1062 </CartContext.Provider>
1063 )
1064 ```
1065
1066 You define the following cart operation functions:
1067
1068 - `addToCart`: Adds an item to the cart by creating a line item.
1069 - `updateItemQuantity`: Updates the quantity of an item in the cart.
1070 - `removeItem`: Removes an item from the cart.
1071 - `refreshCart`: Refreshes the cart data from the backend.
1072 - `clearCart`: Clears the cart and creates a new one.
1073
1074 You also add a `return` statement providing the context values to child components using the `CartContext.Provider`.
1075
1076 Finally, you'll create a custom hook in the same file to access the cart context easily. Replace the `// TODO add useCart hook` comment with the following:
1077
1078 ```tsx title="context/cart-context.tsx"
1079 export function useCart() {
1080 const context = useContext(CartContext)
1081 if (!context) {
1082 throw new Error("useCart must be used within a CartProvider")
1083 }
1084 return context
1085 }
1086 ```
1087
1088 The `useCart` hook retrieves the context value using `useContext`. It throws an error if used outside of a `CartProvider`.
1089
1090 ### Wrap App in Cart Provider
1091
1092 Next, you'll wrap the app in the `CartProvider` to provide the cart context to all components.
1093
1094 In `app/_layout.tsx`, add the following import at the top of the file:
1095
1096 ```tsx title="app/_layout.tsx"
1097 import { CartProvider } from "@/context/cart-context"
1098 ```
1099
1100 Then, in the `RootLayout`'s `return` statement, add the `CartProvider` as a child of the `RegionProvider` and a parent of the `Stack` component:
1101
1102 ```tsx title="app/_layout.tsx" highlights={[["5"]]}
1103 return (
1104 <GestureHandlerRootView style={{ flex: 1 }}>
1105 <ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
1106 <RegionProvider>
1107 <CartProvider>
1108 <Stack screenOptions={{ headerShown: false }}>
1109 <Stack.Screen name="(drawer)" options={{ headerShown: false }} />
1110 </Stack>
1111 <StatusBar style="auto" />
1112 </CartProvider>
1113 </RegionProvider>
1114 </ThemeProvider>
1115 </GestureHandlerRootView>
1116 )
1117 ```
1118
1119 Child components can now access the cart context using the `useCart` hook.
1120
1121 ---
1122
1123 ## Step 8: Create Home Screen
1124
1125 In this step, you'll create the home screen of the app. It will display a hero image with a list of products retrieved from the Medusa backend.
1126
1127 To implement the home screen, you'll create:
1128
1129 1. Necessary utilities and components for the home screen.
1130 2. The home screen and navigation setup.
1131
1132 ### Add Price Formatting Utility
1133
1134 First, you'll create a utility function to format prices based on the selected region's currency.
1135
1136 Create the file `lib/format-price.ts` with the following content:
1137
1138 ```ts title="lib/format-price.ts"
1139 /**
1140 * Format a price amount with currency code
1141 * Note: Medusa stores prices in major units (e.g., dollars, euros)
1142 * so no conversion is needed
1143 */
1144 export function formatPrice(
1145 amount: number | undefined,
1146 currencyCode: string | undefined
1147 ): string {
1148 if (amount === undefined || !currencyCode) {
1149 return "N/A"
1150 }
1151
1152 return new Intl.NumberFormat("en-US", {
1153 style: "currency",
1154 currency: currencyCode.toUpperCase(),
1155 }).format(amount)
1156 }
1157 ```
1158
1159 The `formatPrice` function takes an amount and a currency code as parameters. It formats the amount using the `Intl.NumberFormat` API to display it in the appropriate currency format.
1160
1161 ### Add Loading Component
1162
1163 Next, you'll create a loading component that can be reused across the app to indicate loading states.
1164
1165 Create the file `components/loading.tsx` with the following content:
1166
1167 ```tsx title="components/loading.tsx"
1168 import { Colors } from "@/constants/theme"
1169 import { useColorScheme } from "@/hooks/use-color-scheme"
1170 import React from "react"
1171 import { ActivityIndicator, StyleSheet, Text, View } from "react-native"
1172
1173 interface LoadingProps {
1174 message?: string;
1175 }
1176
1177 export function Loading({ message }: LoadingProps) {
1178 const colorScheme = useColorScheme()
1179 const colors = Colors[colorScheme ?? "light"]
1180
1181 return (
1182 <View style={styles.container}>
1183 <ActivityIndicator size="large" color={colors.tint} />
1184 {message && (
1185 <Text style={[styles.message, { color: colors.text }]}>{message}</Text>
1186 )}
1187 </View>
1188 )
1189 }
1190
1191 const styles = StyleSheet.create({
1192 container: {
1193 flex: 1,
1194 justifyContent: "center",
1195 alignItems: "center",
1196 padding: 20,
1197 },
1198 message: {
1199 marginTop: 12,
1200 fontSize: 16,
1201 },
1202 })
1203 ```
1204
1205 The `Loading` component displays a spinner and an optional message.
1206
1207 ### Add Product Card Component
1208
1209 Next, you'll create a product card component to display individual products on the home screen.
1210
1211 Create the file `components/product-card.tsx` with the following content:
1212
1213 ```tsx title="components/product-card.tsx" collapsibleLines="58-93" expandButtonLabel="Show Styles"
1214 import { Colors } from "@/constants/theme"
1215 import { useRegion } from "@/context/region-context"
1216 import { useColorScheme } from "@/hooks/use-color-scheme"
1217 import { formatPrice } from "@/lib/format-price"
1218 import type { HttpTypes } from "@medusajs/types"
1219 import { Image } from "expo-image"
1220 import { useRouter } from "expo-router"
1221 import React from "react"
1222 import { StyleSheet, Text, TouchableOpacity, View } from "react-native"
1223
1224 interface ProductCardProps {
1225 product: HttpTypes.StoreProduct;
1226 }
1227
1228 export const ProductCard = React.memo(function ProductCard({ product }: ProductCardProps) {
1229 const router = useRouter()
1230 const colorScheme = useColorScheme()
1231 const colors = Colors[colorScheme ?? "light"]
1232 const { selectedRegion } = useRegion()
1233
1234 const thumbnail = product.thumbnail || product.images?.[0]?.url
1235 const variant = product.variants?.[0]
1236
1237 // Get price from calculated_price.calculated_amount
1238 const priceAmount = variant?.calculated_price?.calculated_amount || 0
1239
1240 // Use selected region's currency code
1241 const currencyCode = selectedRegion?.currency_code
1242
1243 return (
1244 <TouchableOpacity
1245 style={[styles.card, { backgroundColor: colors.background }]}
1246 onPress={() => router.push({
1247 pathname: `/(home)/product/${product.id}` as any,
1248 params: { title: product.title },
1249 })}
1250 activeOpacity={0.7}
1251 >
1252 <Image
1253 source={{ uri: thumbnail || "https://placehold.co/200" }}
1254 style={[styles.image, { backgroundColor: colors.imagePlaceholder }]}
1255 contentFit="cover"
1256 />
1257 <View style={styles.content}>
1258 <Text
1259 style={[styles.title, { color: colors.text }]}
1260 numberOfLines={2}
1261 >
1262 {product.title}
1263 </Text>
1264 <View style={styles.priceRow}>
1265 <Text style={[styles.price, { color: colors.tint }]}>
1266 {formatPrice(priceAmount, currencyCode)}
1267 </Text>
1268 </View>
1269 </View>
1270 </TouchableOpacity>
1271 )
1272 })
1273
1274 const styles = StyleSheet.create({
1275 card: {
1276 flex: 1,
1277 margin: 8,
1278 overflow: "hidden",
1279 shadowColor: "#000",
1280 shadowOffset: { width: 0, height: 2 },
1281 shadowOpacity: 0.1,
1282 shadowRadius: 4,
1283 elevation: 3,
1284 },
1285 image: {
1286 width: "100%",
1287 height: 180,
1288 borderRadius: 8,
1289 },
1290 content: {
1291 padding: 12,
1292 },
1293 title: {
1294 fontSize: 14,
1295 fontWeight: "600",
1296 marginBottom: 12,
1297 },
1298 priceRow: {
1299 flexDirection: "row",
1300 alignItems: "center",
1301 justifyContent: "space-between",
1302 gap: 8,
1303 },
1304 price: {
1305 fontSize: 14,
1306 fontWeight: "400",
1307 flex: 1,
1308 },
1309 })
1310 ```
1311
1312 The `ProductCard` component receives a product as a prop.
1313
1314 It displays the product's thumbnail image, title, and price formatted using the `formatPrice` utility. When the card is pressed, it navigates to the product detail screen that you'll add later.
1315
1316 ### Add Home Screen
1317
1318 Next, you'll add the home screen that displays a hero image and a list of products.
1319
1320 Your app will have a tab-based navigation structure, with a tab for the home screen, and another you'll add later for the cart.
1321
1322 So, to set up the tab navigation within the drawer navigator, create the directory `app/(drawer)/(tabs)`.
1323
1324 Then, to create the home screen, create the file `app/(drawer)/(tabs)/(home)/index.tsx` with the following content:
1325
1326 export const homeScreenHighlights = [
1327 ["22", "fetchProducts", "Fetch products from the Medusa backend based on the selected region."],
1328 ["42", "useEffect", "Fetch products when the selected region changes."],
1329 ["48", "onRefresh", "Handle pull-to-refresh to reload products."]
1330 ]
1331
1332 ```tsx title="app/(drawer)/(tabs)/(home)/index.tsx" collapsibleLines="56-98" expandButtonLabel="Show Styles" highlights={homeScreenHighlights}
1333 import { Loading } from "@/components/loading"
1334 import { ProductCard } from "@/components/product-card"
1335 import { Colors } from "@/constants/theme"
1336 import { useRegion } from "@/context/region-context"
1337 import { useColorScheme } from "@/hooks/use-color-scheme"
1338 import { sdk } from "@/lib/sdk"
1339 import type { HttpTypes } from "@medusajs/types"
1340 import { Image } from "expo-image"
1341 import React, { useCallback, useEffect, useState } from "react"
1342 import { FlatList, RefreshControl, StyleSheet, Text, View } from "react-native"
1343
1344 export default function HomeScreen() {
1345 const colorScheme = useColorScheme()
1346 const colors = Colors[colorScheme ?? "light"]
1347 const { selectedRegion } = useRegion()
1348
1349 const [products, setProducts] = useState<HttpTypes.StoreProduct[]>([])
1350 const [loading, setLoading] = useState(true)
1351 const [refreshing, setRefreshing] = useState(false)
1352 const [error, setError] = useState<string | null>(null)
1353
1354 const fetchProducts = useCallback(async () => {
1355 try {
1356 setLoading(true)
1357 setError(null)
1358
1359 const { products: fetchedProducts } = await sdk.store.product.list({
1360 region_id: selectedRegion?.id,
1361 fields: "*variants.calculated_price,+variants.inventory_quantity",
1362 })
1363
1364 setProducts(fetchedProducts)
1365 } catch (err) {
1366 console.error("Failed to fetch products:", err)
1367 setError("Failed to load products. Please try again.")
1368 } finally {
1369 setLoading(false)
1370 setRefreshing(false)
1371 }
1372 }, [selectedRegion])
1373
1374 useEffect(() => {
1375 if (selectedRegion) {
1376 fetchProducts()
1377 }
1378 }, [selectedRegion, fetchProducts])
1379
1380 const onRefresh = () => {
1381 setRefreshing(true)
1382 fetchProducts()
1383 }
1384
1385 // TODO add return statement
1386 }
1387
1388 const styles = StyleSheet.create({
1389 container: {
1390 flex: 1,
1391 },
1392 centerContainer: {
1393 flex: 1,
1394 justifyContent: "center",
1395 alignItems: "center",
1396 padding: 20,
1397 },
1398 header: {
1399 width: "100%",
1400 },
1401 banner: {
1402 width: "100%",
1403 height: 200,
1404 },
1405 sectionTitle: {
1406 fontSize: 24,
1407 fontWeight: "700",
1408 marginTop: 24,
1409 marginBottom: 16,
1410 paddingHorizontal: 16,
1411 },
1412 listContent: {
1413 paddingBottom: 20,
1414 },
1415 row: {
1416 justifyContent: "space-between",
1417 paddingHorizontal: 8,
1418 },
1419 errorText: {
1420 fontSize: 16,
1421 textAlign: "center",
1422 },
1423 emptyContainer: {
1424 padding: 40,
1425 alignItems: "center",
1426 },
1427 emptyText: {
1428 fontSize: 16,
1429 },
1430 })
1431 ```
1432
1433 The home screen component fetches products from the Medusa backend based on the selected region. It manages loading, refreshing, and error states.
1434
1435 Next, you'll add the return statement to render the home screen UI. Replace the `// TODO add return statement` comment with the following:
1436
1437 ```tsx title="app/(drawer)/(tabs)/(home)/index.tsx"
1438 if (loading) {
1439 return <Loading message="Loading products..." />
1440 }
1441
1442 if (error) {
1443 return (
1444 <View style={[styles.centerContainer, { backgroundColor: colors.background }]}>
1445 <Text style={[styles.errorText, { color: colors.text }]}>{error}</Text>
1446 </View>
1447 )
1448 }
1449
1450 return (
1451 <View style={[styles.container, { backgroundColor: colors.background }]}>
1452 <FlatList
1453 data={products}
1454 keyExtractor={(item) => item.id}
1455 numColumns={2}
1456 columnWrapperStyle={styles.row}
1457 initialNumToRender={6}
1458 maxToRenderPerBatch={6}
1459 windowSize={5}
1460 removeClippedSubviews={true}
1461 ListHeaderComponent={
1462 <View style={styles.header}>
1463 <Image
1464 source={{ uri: "https://images.unsplash.com/photo-1600185365483-26d7a4cc7519?w=800" }}
1465 style={[styles.banner, { backgroundColor: colors.imagePlaceholder }]}
1466 contentFit="cover"
1467 />
1468 <Text style={[styles.sectionTitle, { color: colors.text }]}>
1469 Latest Products
1470 </Text>
1471 </View>
1472 }
1473 renderItem={({ item }) => <ProductCard product={item} />}
1474 contentContainerStyle={styles.listContent}
1475 refreshControl={
1476 <RefreshControl
1477 refreshing={refreshing}
1478 onRefresh={onRefresh}
1479 tintColor={colors.tint}
1480 />
1481 }
1482 ListEmptyComponent={
1483 <View style={styles.emptyContainer}>
1484 <Text style={[styles.emptyText, { color: colors.text }]}>
1485 No products available
1486 </Text>
1487 </View>
1488 }
1489 />
1490 </View>
1491 )
1492 ```
1493
1494 You handle three main states in the return statement:
1495
1496 1. Loading State: If the products are still loading, you display the `Loading` component with a message.
1497 2. Error State: If there was an error fetching the products, you display an error message.
1498 3. Success State: If the products are successfully fetched, you render a `FlatList` to display the products in a grid layout. The list includes a header with a hero image and a section title.
1499
1500 You also configure the `FlatList` to support pull-to-refresh functionality and handle empty states.
1501
1502 Next, you'll add stack navigation for the home screen, which will later allow you to add a product detail screen.
1503
1504 Create the file `app/(drawer)/(tabs)/(home)/_layout.tsx` with the following content:
1505
1506 ```tsx title="app/(drawer)/(tabs)/(home)/_layout.tsx"
1507 import { useColorScheme } from "@/hooks/use-color-scheme"
1508 import { DrawerActions } from "@react-navigation/native"
1509 import { Stack, useNavigation } from "expo-router"
1510 import React from "react"
1511 import { TouchableOpacity } from "react-native"
1512
1513 import { IconSymbol } from "@/components/ui/icon-symbol"
1514 import { Colors } from "@/constants/theme"
1515
1516 export default function HomeStackLayout() {
1517 const colorScheme = useColorScheme()
1518 const navigation = useNavigation()
1519 const colors = Colors[colorScheme ?? "light"]
1520
1521 return (
1522 <Stack
1523 screenOptions={{
1524 headerShown: true,
1525 }}
1526 >
1527 <Stack.Screen
1528 name="index"
1529 options={{
1530 title: "Medusa Store",
1531 headerLeft: () => (
1532 <TouchableOpacity
1533 onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
1534 style={{ height: 36, width: 36, display: "flex", alignItems: "center", justifyContent: "center" }}
1535 >
1536 <IconSymbol size={28} name="line.3.horizontal" color={colors.icon} />
1537 </TouchableOpacity>
1538 ),
1539 }}
1540 />
1541 {/* TODO add product details screen */}
1542 </Stack>
1543 )
1544 }
1545 ```
1546
1547 The `HomeStackLayout` component sets up a stack navigator for the home screen. It adds a header with a title and a menu button to open the drawer navigator.
1548
1549 Next, you'll add the tab navigation layout to include the home screen tab.
1550
1551 Create the file `app/(drawer)/(tabs)/_layout.tsx` with the following content:
1552
1553 ```tsx title="app/(drawer)/(tabs)/_layout.tsx"
1554 import { useColorScheme } from "@/hooks/use-color-scheme"
1555 import { Tabs } from "expo-router"
1556 import React from "react"
1557
1558 import { HapticTab } from "@/components/haptic-tab"
1559 import { IconSymbol } from "@/components/ui/icon-symbol"
1560 import { Colors } from "@/constants/theme"
1561
1562 export default function TabLayout() {
1563 const colorScheme = useColorScheme()
1564
1565 return (
1566 <Tabs
1567 screenOptions={{
1568 tabBarActiveTintColor: Colors[colorScheme ?? "light"].tint,
1569 headerShown: true,
1570 tabBarButton: HapticTab,
1571 }}>
1572 <Tabs.Screen
1573 name="index"
1574 options={{
1575 href: null,
1576 }}
1577 />
1578 <Tabs.Screen
1579 name="(home)"
1580 options={{
1581 title: "Medusa Store",
1582 tabBarIcon: ({ color }) => <IconSymbol size={28} name="house.fill" color={color} />,
1583 headerShown: false, // Let the home stack manage its own headers
1584 }}
1585 />
1586 {/* TODO add cart tab */}
1587 </Tabs>
1588 )
1589 }
1590 ```
1591
1592 The `TabLayout` component sets up a tab navigator using Expo Router's `Tabs` component. It adds a tab for the home screen with an icon and title.
1593
1594 An `index` tab is also specified to redirect to the home screen, ensuring it's always the default tab when the app opens.
1595
1596 So, create the file `app/(drawer)/(tabs)/index.tsx` with the following content:
1597
1598 ```tsx title="app/(drawer)/(tabs)/index.tsx"
1599 import { Redirect } from "expo-router"
1600 import React from "react"
1601
1602 const MainScreen = () => {
1603 return <Redirect href="/(drawer)/(tabs)/(home)" />
1604 }
1605
1606 export default MainScreen
1607 ```
1608
1609 The `MainScreen` component redirects to the home screen tab when accessed.
1610
1611 <Note>
1612
1613 If you get a type error regarding the `href` prop in the `Redirect` component, wait until the next time you run the project. The Expo Router types should update and the error should go away.
1614
1615 </Note>
1616
1617 ### Add Tabs to Drawer Navigator
1618
1619 Finally, you'll add the tab navigator to the drawer navigator.
1620
1621 In `app/(drawer)/_layout.tsx`, update the `return` statement to replace the `TODO` comment with the tabs screen:
1622
1623 ```tsx title="app/(drawer)/_layout.tsx"
1624 return (
1625 <Drawer
1626 drawerContent={(props) => <DrawerContent {...props} />}
1627 screenOptions={{
1628 headerShown: false,
1629 drawerPosition: "left",
1630 }}
1631 >
1632 <Drawer.Screen
1633 name="(tabs)"
1634 options={{
1635 drawerLabel: "Home",
1636 title: "Shop",
1637 }}
1638 />
1639 </Drawer>
1640 )
1641 ```
1642
1643 The drawer navigator now includes the tab navigator as its main screen.
1644
1645 ### Test the Home Screen
1646
1647 You can now test the home screen of your app.
1648
1649 There are different ways to run the React Native app, which you can learn about in [Expo's documentation](https://docs.expo.dev/get-started/set-up-your-environment/?platform=ios&device=physical&mode=expo-go). The recommended way is to install the [Expo Go](https://expo.dev/go) app on your mobile device and run the app on it.
1650
1651 Before you run your app, start the Medusa backend by running the following command in the Medusa project directory:
1652
1653 ```bash badgeLabel="Medusa Application" badgeColor="green"
1654 npm run dev
1655 ```
1656
1657 Then, run the following command in your Expo project directory to start the Expo server:
1658
1659 ```bash badgeLabel="Expo Application" badgeColor="blue"
1660 npm run start
1661 ```
1662
1663 In the terminal, you should see a QR code. Scan it using your device to open the app in Expo Go.
1664
1665 When the app opens, you'll see a home screen displaying a hero image and a list of products fetched from the Medusa application.
1666
1667 <Note>
1668
1669 Clicking on a product won't do anything yet, as you haven't implemented the product detail screen. You'll add it in the next step.
1670
1671 </Note>
1672
1673 ![Home screen showing the hero image and list of products](https://res.cloudinary.com/dza7lstvk/image/upload/v1762344360/Medusa%20Resources/CleanShot_2025-11-05_at_13.54.13_2x_efopgu.png)
1674
1675 If you click the menu icon in the top-left corner, the drawer navigator will open, allowing you to select the region using the region selector you implemented earlier.
1676
1677 ![Drawer navigator showing the region selector](https://res.cloudinary.com/dza7lstvk/image/upload/v1762344361/Medusa%20Resources/CleanShot_2025-11-05_at_13.54.38_2x_r0tb6i.png)
1678
1679 ---
1680
1681 ## Step 9: Create Product Detail Screen
1682
1683 In this step, you'll create the product detail screen that displays detailed information about a selected product.
1684
1685 You'll create the necessary components and utilities first, then implement the product detail screen and navigation.
1686
1687 ### Add Button Component
1688
1689 First, you'll create a button component that can be reused across the app.
1690
1691 Create the file `components/ui/button.tsx` with the following content:
1692
1693 ```tsx title="components/ui/button.tsx" collapsibleLines="63-84" expandButtonLabel="Show Styles"
1694 import { Colors } from "@/constants/theme"
1695 import { useColorScheme } from "@/hooks/use-color-scheme"
1696 import React from "react"
1697 import {
1698 ActivityIndicator,
1699 StyleSheet,
1700 Text,
1701 TouchableOpacity,
1702 TouchableOpacityProps,
1703 } from "react-native"
1704
1705 interface ButtonProps extends TouchableOpacityProps {
1706 title: string;
1707 variant?: "primary" | "secondary";
1708 loading?: boolean;
1709 }
1710
1711 export function Button({
1712 title,
1713 variant = "primary",
1714 loading = false,
1715 disabled,
1716 style,
1717 ...props
1718 }: ButtonProps) {
1719 const colorScheme = useColorScheme()
1720 const colors = Colors[colorScheme ?? "light"]
1721
1722 const isPrimary = variant === "primary"
1723 const isDisabled = disabled || loading
1724
1725 // Primary button: white background with dark text in dark mode, tint background with white text in light mode
1726 const primaryBgColor = colorScheme === "dark" ? "#fff" : colors.tint
1727 const primaryTextColor = colorScheme === "dark" ? "#000" : "#fff"
1728
1729 return (
1730 <TouchableOpacity
1731 style={[
1732 styles.button,
1733 isPrimary ? { backgroundColor: primaryBgColor } : styles.secondaryButton,
1734 isDisabled && styles.disabled,
1735 style,
1736 ]}
1737 disabled={isDisabled}
1738 {...props}
1739 >
1740 {loading ? (
1741 <ActivityIndicator color={isPrimary ? primaryTextColor : colors.tint} />
1742 ) : (
1743 <Text
1744 style={[
1745 styles.text,
1746 isPrimary ? { color: primaryTextColor } : { color: colors.tint },
1747 ]}
1748 >
1749 {title}
1750 </Text>
1751 )}
1752 </TouchableOpacity>
1753 )
1754 }
1755
1756 const styles = StyleSheet.create({
1757 button: {
1758 paddingVertical: 14,
1759 paddingHorizontal: 24,
1760 borderRadius: 8,
1761 alignItems: "center",
1762 justifyContent: "center",
1763 minHeight: 48,
1764 },
1765 secondaryButton: {
1766 backgroundColor: "transparent",
1767 borderWidth: 1,
1768 borderColor: "#ccc",
1769 },
1770 text: {
1771 fontSize: 16,
1772 fontWeight: "600",
1773 },
1774 disabled: {
1775 opacity: 0.5,
1776 },
1777 })
1778 ```
1779
1780 The `Button` component accepts props for the title, variant (primary or secondary), loading state, and other touchable opacity props.
1781
1782 ### Add Product Image Slider Component
1783
1784 Next, you'll create a product image slider component to display multiple images of a product.
1785
1786 Create the file `components/product-image-slider.tsx` with the following content:
1787
1788 ```tsx title="components/product-image-slider.tsx" collapsibleLines="77-103" expandButtonLabel="Show Styles"
1789 import { Colors } from "@/constants/theme"
1790 import { useColorScheme } from "@/hooks/use-color-scheme"
1791 import { Image } from "expo-image"
1792 import React, { useRef, useState } from "react"
1793 import { Dimensions, FlatList, StyleSheet, View } from "react-native"
1794
1795 const { width: SCREEN_WIDTH } = Dimensions.get("window")
1796
1797 interface ProductImageSliderProps {
1798 images: string[];
1799 }
1800
1801 export function ProductImageSlider({ images }: ProductImageSliderProps) {
1802 const colorScheme = useColorScheme()
1803 const colors = Colors[colorScheme ?? "light"]
1804 const [currentImageIndex, setCurrentImageIndex] = useState(0)
1805 const imageListRef = useRef<FlatList>(null)
1806
1807 const onViewableItemsChanged = useRef(({ viewableItems }: any) => {
1808 if (viewableItems.length > 0) {
1809 setCurrentImageIndex(viewableItems[0].index || 0)
1810 }
1811 }).current
1812
1813 const viewabilityConfig = useRef({
1814 itemVisiblePercentThreshold: 50,
1815 }).current
1816
1817 const renderImageItem = ({ item }: { item: string }) => (
1818 <View style={styles.imageSlide}>
1819 <Image
1820 source={{ uri: item }}
1821 style={[styles.image, { backgroundColor: colors.imagePlaceholder }]}
1822 contentFit="cover"
1823 />
1824 </View>
1825 )
1826
1827 if (images.length === 0) {
1828 return null
1829 }
1830
1831 return (
1832 <View style={styles.container}>
1833 <FlatList
1834 ref={imageListRef}
1835 data={images}
1836 renderItem={renderImageItem}
1837 keyExtractor={(item, index) => `image-${index}`}
1838 horizontal
1839 pagingEnabled
1840 showsHorizontalScrollIndicator={false}
1841 onViewableItemsChanged={onViewableItemsChanged}
1842 viewabilityConfig={viewabilityConfig}
1843 />
1844 {images.length > 1 && (
1845 <View style={styles.pagination}>
1846 {images.map((_, index) => (
1847 <View
1848 key={index}
1849 style={[
1850 styles.paginationDot,
1851 {
1852 backgroundColor: currentImageIndex === index
1853 ? colors.tint
1854 : colors.icon + "40",
1855 },
1856 ]}
1857 />
1858 ))}
1859 </View>
1860 )}
1861 </View>
1862 )
1863 }
1864
1865 const styles = StyleSheet.create({
1866 container: {
1867 position: "relative",
1868 },
1869 imageSlide: {
1870 width: SCREEN_WIDTH,
1871 },
1872 image: {
1873 width: SCREEN_WIDTH,
1874 height: 400,
1875 },
1876 pagination: {
1877 position: "absolute",
1878 bottom: 16,
1879 left: 0,
1880 right: 0,
1881 flexDirection: "row",
1882 justifyContent: "center",
1883 alignItems: "center",
1884 gap: 6,
1885 },
1886 paginationDot: {
1887 width: 8,
1888 height: 8,
1889 borderRadius: 4,
1890 },
1891 })
1892 ```
1893
1894 The `ProductImageSlider` component receives an array of image URLs as a prop and displays them in a horizontally scrollable `FlatList`. It also includes pagination dots to indicate the current image being viewed.
1895
1896 ### Add Product Skeleton Component
1897
1898 Next, you'll create a skeleton component to display while the product details are loading. This improves the user experience by providing a visual placeholder.
1899
1900 Create the file `components/product-skeleton.tsx` with the following content:
1901
1902 ```tsx title="components/product-skeleton.tsx" collapsibleLines="160-256" expandButtonLabel="Show Styles"
1903 import { Colors } from "@/constants/theme"
1904 import { useColorScheme } from "@/hooks/use-color-scheme"
1905 import React, { useEffect, useRef } from "react"
1906 import { Animated, StyleSheet, View } from "react-native"
1907
1908 export function ProductSkeleton() {
1909 const colorScheme = useColorScheme()
1910 const colors = Colors[colorScheme ?? "light"]
1911 const shimmerAnim = useRef(new Animated.Value(0)).current
1912
1913 useEffect(() => {
1914 Animated.loop(
1915 Animated.sequence([
1916 Animated.timing(shimmerAnim, {
1917 toValue: 1,
1918 duration: 1000,
1919 useNativeDriver: true,
1920 }),
1921 Animated.timing(shimmerAnim, {
1922 toValue: 0,
1923 duration: 1000,
1924 useNativeDriver: true,
1925 }),
1926 ])
1927 ).start()
1928 }, [shimmerAnim])
1929
1930 const opacity = shimmerAnim.interpolate({
1931 inputRange: [0, 1],
1932 outputRange: [0.3, 0.7],
1933 })
1934
1935 const skeletonColor = colorScheme === "dark" ? "#333" : "#e0e0e0"
1936
1937 return (
1938 <View style={[styles.container, { backgroundColor: colors.background }]}>
1939 {/* Main Image Skeleton with Pagination Dots */}
1940 <View style={styles.imageContainer}>
1941 <Animated.View
1942 style={[
1943 styles.imageSkeleton,
1944 { backgroundColor: skeletonColor, opacity },
1945 ]}
1946 />
1947 <View style={styles.pagination}>
1948 {[1, 2, 3].map((i) => (
1949 <Animated.View
1950 key={i}
1951 style={[
1952 styles.paginationDot,
1953 { backgroundColor: skeletonColor, opacity },
1954 ]}
1955 />
1956 ))}
1957 </View>
1958 </View>
1959
1960 <View style={styles.content}>
1961 {/* Title Skeleton */}
1962 <Animated.View
1963 style={[
1964 styles.titleSkeleton,
1965 { backgroundColor: skeletonColor, opacity },
1966 ]}
1967 />
1968
1969 {/* Description Skeleton - 3 lines */}
1970 <View style={styles.descriptionContainer}>
1971 <Animated.View
1972 style={[
1973 styles.descriptionLine,
1974 { backgroundColor: skeletonColor, opacity, width: "100%" },
1975 ]}
1976 />
1977 <Animated.View
1978 style={[
1979 styles.descriptionLine,
1980 { backgroundColor: skeletonColor, opacity, width: "90%" },
1981 ]}
1982 />
1983 <Animated.View
1984 style={[
1985 styles.descriptionLine,
1986 { backgroundColor: skeletonColor, opacity, width: "70%" },
1987 ]}
1988 />
1989 </View>
1990
1991 {/* Price Skeleton */}
1992 <Animated.View
1993 style={[
1994 styles.priceSkeleton,
1995 { backgroundColor: skeletonColor, opacity },
1996 ]}
1997 />
1998
1999 {/* Options Skeleton */}
2000 <View style={styles.optionsContainer}>
2001 <Animated.View
2002 style={[
2003 styles.optionTitleSkeleton,
2004 { backgroundColor: skeletonColor, opacity },
2005 ]}
2006 />
2007 <View style={styles.optionButtons}>
2008 {[1, 2, 3].map((i) => (
2009 <Animated.View
2010 key={i}
2011 style={[
2012 styles.optionButtonSkeleton,
2013 { backgroundColor: skeletonColor, opacity },
2014 ]}
2015 />
2016 ))}
2017 </View>
2018 </View>
2019
2020 {/* Quantity Skeleton */}
2021 <View style={styles.quantityContainer}>
2022 <Animated.View
2023 style={[
2024 styles.quantityLabelSkeleton,
2025 { backgroundColor: skeletonColor, opacity },
2026 ]}
2027 />
2028 <View style={styles.quantityControls}>
2029 <Animated.View
2030 style={[
2031 styles.quantityButtonSkeleton,
2032 { backgroundColor: skeletonColor, opacity },
2033 ]}
2034 />
2035 <Animated.View
2036 style={[
2037 styles.quantityValueSkeleton,
2038 { backgroundColor: skeletonColor, opacity },
2039 ]}
2040 />
2041 <Animated.View
2042 style={[
2043 styles.quantityButtonSkeleton,
2044 { backgroundColor: skeletonColor, opacity },
2045 ]}
2046 />
2047 </View>
2048 </View>
2049
2050 {/* Add to Cart Button Skeleton */}
2051 <Animated.View
2052 style={[
2053 styles.buttonSkeleton,
2054 { backgroundColor: skeletonColor, opacity },
2055 ]}
2056 />
2057 </View>
2058 </View>
2059 )
2060 }
2061
2062 const styles = StyleSheet.create({
2063 container: {
2064 flex: 1,
2065 },
2066 imageContainer: {
2067 position: "relative",
2068 },
2069 imageSkeleton: {
2070 width: "100%",
2071 height: 400,
2072 },
2073 pagination: {
2074 position: "absolute",
2075 bottom: 16,
2076 left: 0,
2077 right: 0,
2078 flexDirection: "row",
2079 justifyContent: "center",
2080 alignItems: "center",
2081 gap: 6,
2082 },
2083 paginationDot: {
2084 width: 8,
2085 height: 8,
2086 borderRadius: 4,
2087 },
2088 content: {
2089 padding: 20,
2090 },
2091 titleSkeleton: {
2092 height: 32,
2093 width: "70%",
2094 borderRadius: 4,
2095 marginBottom: 12,
2096 },
2097 descriptionContainer: {
2098 marginBottom: 20,
2099 },
2100 descriptionLine: {
2101 height: 16,
2102 borderRadius: 4,
2103 marginBottom: 8,
2104 },
2105 priceSkeleton: {
2106 height: 36,
2107 width: "40%",
2108 borderRadius: 4,
2109 marginBottom: 24,
2110 },
2111 optionsContainer: {
2112 marginBottom: 24,
2113 },
2114 optionTitleSkeleton: {
2115 height: 20,
2116 width: "30%",
2117 borderRadius: 4,
2118 marginBottom: 12,
2119 },
2120 optionButtons: {
2121 flexDirection: "row",
2122 gap: 8,
2123 },
2124 optionButtonSkeleton: {
2125 height: 40,
2126 width: 80,
2127 borderRadius: 8,
2128 },
2129 quantityContainer: {
2130 marginBottom: 32,
2131 },
2132 quantityLabelSkeleton: {
2133 height: 20,
2134 width: "25%",
2135 borderRadius: 4,
2136 marginBottom: 12,
2137 },
2138 quantityControls: {
2139 flexDirection: "row",
2140 alignItems: "center",
2141 },
2142 quantityButtonSkeleton: {
2143 width: 36,
2144 height: 36,
2145 borderRadius: 18,
2146 },
2147 quantityValueSkeleton: {
2148 width: 30,
2149 height: 20,
2150 borderRadius: 4,
2151 marginHorizontal: 20,
2152 },
2153 buttonSkeleton: {
2154 height: 48,
2155 borderRadius: 8,
2156 marginTop: 8,
2157 },
2158 })
2159 ```
2160
2161 The `ProductSkeleton` component uses animated views to create a shimmering effect for various sections of the product detail screen, including the image, title, and buttons.
2162
2163 ### Add Toast Component
2164
2165 Next, you'll create a toast component to display brief messages to the user, such as confirming that an item has been added to the cart.
2166
2167 Create the file `components/ui/toast.tsx` with the following content:
2168
2169 ```tsx title="components/ui/toast.tsx" collapsibleLines="91-116" expandButtonLabel="Show Styles"
2170 import { useColorScheme } from "@/hooks/use-color-scheme"
2171 import React, { useCallback, useEffect, useRef } from "react"
2172 import { Animated, StyleSheet, Text, View } from "react-native"
2173
2174 interface ToastProps {
2175 message: string;
2176 visible: boolean;
2177 onHide: () => void;
2178 duration?: number;
2179 type?: "success" | "error" | "info";
2180 }
2181
2182 export function Toast({
2183 message,
2184 visible,
2185 onHide,
2186 duration = 3000,
2187 type = "success",
2188 }: ToastProps) {
2189 const colorScheme = useColorScheme()
2190 const opacity = useRef(new Animated.Value(0)).current
2191 const translateY = useRef(new Animated.Value(50)).current
2192
2193 const hideToast = useCallback(() => {
2194 Animated.parallel([
2195 Animated.timing(opacity, {
2196 toValue: 0,
2197 duration: 300,
2198 useNativeDriver: true,
2199 }),
2200 Animated.timing(translateY, {
2201 toValue: 50,
2202 duration: 300,
2203 useNativeDriver: true,
2204 }),
2205 ]).start(() => {
2206 onHide()
2207 })
2208 }, [opacity, translateY, onHide])
2209
2210 useEffect(() => {
2211 if (visible) {
2212 // Fade in and slide up
2213 Animated.parallel([
2214 Animated.timing(opacity, {
2215 toValue: 1,
2216 duration: 300,
2217 useNativeDriver: true,
2218 }),
2219 Animated.timing(translateY, {
2220 toValue: 0,
2221 duration: 300,
2222 useNativeDriver: true,
2223 }),
2224 ]).start()
2225
2226 // Auto hide after duration
2227 const timer = setTimeout(() => {
2228 hideToast()
2229 }, duration)
2230
2231 return () => clearTimeout(timer)
2232 }
2233 }, [visible, duration, opacity, translateY, hideToast])
2234
2235 if (!visible) {
2236 return null
2237 }
2238
2239 // Use inverted colors for minimal design: white in dark mode, black in light mode
2240 const backgroundColor = colorScheme === "dark" ? "#fff" : "#000"
2241 const textColor = colorScheme === "dark" ? "#000" : "#fff"
2242
2243 return (
2244 <Animated.View
2245 style={[
2246 styles.container,
2247 {
2248 opacity,
2249 transform: [{ translateY }],
2250 },
2251 ]}
2252 >
2253 <View style={[styles.toast, { backgroundColor }]}>
2254 <Text style={[styles.message, { color: textColor }]}>{message}</Text>
2255 </View>
2256 </Animated.View>
2257 )
2258 }
2259
2260 const styles = StyleSheet.create({
2261 container: {
2262 position: "absolute",
2263 bottom: 100,
2264 left: 20,
2265 right: 20,
2266 alignItems: "center",
2267 zIndex: 1000,
2268 },
2269 toast: {
2270 paddingHorizontal: 20,
2271 paddingVertical: 14,
2272 borderRadius: 12,
2273 shadowColor: "#000",
2274 shadowOffset: { width: 0, height: 4 },
2275 shadowOpacity: 0.3,
2276 shadowRadius: 8,
2277 elevation: 8,
2278 minWidth: 200,
2279 },
2280 message: {
2281 fontSize: 15,
2282 fontWeight: "600",
2283 textAlign: "center",
2284 },
2285 })
2286 ```
2287
2288 The `Toast` component accepts props for the message, visibility, hide callback, duration, and type. It uses animated values to create fade-in and slide-up effects when the toast appears and disappears.
2289
2290 ### Add Inventory Utility
2291
2292 Next, you'll create a utility function to check if a product variant is in stock.
2293
2294 Create the file `lib/inventory.ts` with the following content:
2295
2296 ```ts title="lib/inventory.ts"
2297 import type { HttpTypes } from "@medusajs/types"
2298
2299 /**
2300 * Check if a product variant is in stock
2301 * A variant is in stock if:
2302 * - manage_inventory is false (inventory tracking disabled), OR
2303 * - inventory_quantity is greater than 0
2304 */
2305 export function isVariantInStock(
2306 variant: HttpTypes.StoreProductVariant | undefined | null
2307 ): boolean {
2308 if (!variant) {
2309 return false
2310 }
2311
2312 return variant.manage_inventory === false || (variant.inventory_quantity || 0) > 0
2313 }
2314 ```
2315
2316 The `isVariantInStock` function checks if a product variant is in stock. A variant is considered in stock if:
2317
2318 - `manage_inventory` is false (inventory tracking is disabled), OR
2319 - `inventory_quantity` is greater than 0.
2320
2321 ### Implement Product Detail Screen
2322
2323 You can now implement the product detail screen using the components and utilities you've created.
2324
2325 Create the file `app/(drawer)/(tabs)/(home)/product/[id].tsx` with the following content:
2326
2327 export const productDetailHighlights = [
2328 ["18", "id", "The product ID from the URL parameters."],
2329 ["21", "addToCart", "Function to add items to the cart from the cart context."],
2330 ["22", "selectedRegion", "The currently selected region from the region context."],
2331 ["24", "product", "The product details fetched from the backend."],
2332 ["25", "selectedOptions", "The currently selected product options, such as size or color."],
2333 ["26", "quantity", "The quantity of the product to add to the cart."],
2334 ["27", "loading", "Loading state for fetching product details."],
2335 ["28", "addingToCart", "Loading state for adding the product to the cart."],
2336 ["29", "error", "Error message if fetching product details fails."],
2337 ]
2338
2339 ```tsx title="app/(drawer)/(tabs)/(home)/product/[id].tsx" collapsibleLines="37-143" expandButtonLabel="Show Styles" highlights={productDetailHighlights}
2340 import { ProductImageSlider } from "@/components/product-image-slider"
2341 import { ProductSkeleton } from "@/components/product-skeleton"
2342 import { Button } from "@/components/ui/button"
2343 import { Toast } from "@/components/ui/toast"
2344 import { Colors } from "@/constants/theme"
2345 import { useCart } from "@/context/cart-context"
2346 import { useRegion } from "@/context/region-context"
2347 import { useColorScheme } from "@/hooks/use-color-scheme"
2348 import { formatPrice } from "@/lib/format-price"
2349 import { isVariantInStock } from "@/lib/inventory"
2350 import { sdk } from "@/lib/sdk"
2351 import type { HttpTypes } from "@medusajs/types"
2352 import { useLocalSearchParams, useNavigation } from "expo-router"
2353 import React, { useCallback, useEffect, useMemo, useState } from "react"
2354 import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native"
2355
2356 export default function ProductDetailsScreen() {
2357 const { id, title } = useLocalSearchParams<{ id: string; title?: string }>()
2358 const colorScheme = useColorScheme()
2359 const colors = Colors[colorScheme ?? "light"]
2360 const { addToCart } = useCart()
2361 const { selectedRegion } = useRegion()
2362
2363 const [product, setProduct] = useState<HttpTypes.StoreProduct | null>(null)
2364 const [selectedOptions, setSelectedOptions] = useState<Record<string, string>>({})
2365 const [quantity, setQuantity] = useState(1)
2366 const [loading, setLoading] = useState(true)
2367 const [addingToCart, setAddingToCart] = useState(false)
2368 const [error, setError] = useState<string | null>(null)
2369 const [toastVisible, setToastVisible] = useState(false)
2370 const [toastMessage, setToastMessage] = useState("")
2371 const navigation = useNavigation()
2372
2373 // TODO fetch product
2374 }
2375
2376 const styles = StyleSheet.create({
2377 container: {
2378 flex: 1,
2379 },
2380 centerContainer: {
2381 flex: 1,
2382 justifyContent: "center",
2383 alignItems: "center",
2384 padding: 20,
2385 },
2386 content: {
2387 padding: 20,
2388 },
2389 title: {
2390 fontSize: 28,
2391 fontWeight: "700",
2392 marginBottom: 12,
2393 },
2394 description: {
2395 fontSize: 16,
2396 lineHeight: 24,
2397 marginBottom: 20,
2398 },
2399 priceContainer: {
2400 marginBottom: 24,
2401 },
2402 price: {
2403 fontSize: 20,
2404 fontWeight: "700",
2405 marginBottom: 8,
2406 },
2407 stockBadge: {
2408 paddingHorizontal: 12,
2409 paddingVertical: 6,
2410 borderRadius: 6,
2411 alignSelf: "flex-start",
2412 },
2413 outOfStockText: {
2414 color: "#fff",
2415 fontSize: 13,
2416 fontWeight: "600",
2417 textTransform: "uppercase",
2418 },
2419 lowStockText: {
2420 color: "#fff",
2421 fontSize: 13,
2422 fontWeight: "600",
2423 },
2424 optionsSection: {
2425 marginBottom: 24,
2426 },
2427 optionGroup: {
2428 marginBottom: 20,
2429 },
2430 sectionTitle: {
2431 fontSize: 18,
2432 fontWeight: "600",
2433 marginBottom: 12,
2434 },
2435 optionValues: {
2436 flexDirection: "row",
2437 flexWrap: "wrap",
2438 gap: 8,
2439 },
2440 optionButton: {
2441 paddingVertical: 10,
2442 paddingHorizontal: 16,
2443 borderRadius: 8,
2444 borderWidth: 1,
2445 },
2446 optionText: {
2447 fontSize: 14,
2448 },
2449 quantitySection: {
2450 marginBottom: 32,
2451 },
2452 quantityControls: {
2453 flexDirection: "row",
2454 alignItems: "center",
2455 },
2456 quantityButton: {
2457 width: 36,
2458 height: 36,
2459 borderRadius: 18,
2460 borderWidth: 1,
2461 alignItems: "center",
2462 justifyContent: "center",
2463 },
2464 quantityButtonText: {
2465 fontSize: 18,
2466 fontWeight: "600",
2467 },
2468 quantity: {
2469 marginHorizontal: 20,
2470 fontSize: 18,
2471 fontWeight: "600",
2472 minWidth: 30,
2473 textAlign: "center",
2474 },
2475 addButton: {
2476 marginTop: 8,
2477 },
2478 errorText: {
2479 fontSize: 16,
2480 textAlign: "center",
2481 },
2482 })
2483 ```
2484
2485 The `ProductDetailsScreen` includes the following variables:
2486
2487 - `id`: The product ID from the URL parameters.
2488 - `colorScheme` and `colors`: For theming based on the current color scheme.
2489 - `addToCart`: Function to add items to the cart from the cart context.
2490 - `selectedRegion`: The currently selected region from the region context.
2491 - `product`: The product details fetched from the backend.
2492 - `selectedOptions`: The currently selected product options, such as size or color.
2493 - `quantity`: The quantity of the product to add to the cart.
2494 - `loading`: Loading state for fetching product details.
2495 - `addingToCart`: Loading state for adding the product to the cart.
2496 - `error`: Error message if fetching product details fails.
2497 - `toastVisible` and `toastMessage`: For displaying toast messages.
2498
2499 Next, you'll implement the logic to fetch the product details based on the product ID. Replace the `// TODO fetch product` comment with the following:
2500
2501 ```tsx title="app/(drawer)/(tabs)/(home)/product/[id].tsx"
2502 const fetchProduct = useCallback(async () => {
2503 try {
2504 setLoading(true)
2505 setError(null)
2506
2507 const { product: fetchedProduct } = await sdk.store.product.retrieve(id, {
2508 fields: "*variants.calculated_price,+variants.inventory_quantity",
2509 region_id: selectedRegion?.id,
2510 })
2511
2512 setProduct(fetchedProduct)
2513
2514 // Initialize selected options with first variant's option values
2515 if (fetchedProduct.variants && fetchedProduct.variants.length > 0) {
2516 const firstVariant = fetchedProduct.variants[0]
2517 const initialOptions: Record<string, string> = {}
2518 firstVariant.options?.forEach((optionValue) => {
2519 if (optionValue.option_id && optionValue.value) {
2520 initialOptions[optionValue.option_id] = optionValue.value
2521 }
2522 })
2523 setSelectedOptions(initialOptions)
2524 }
2525 } catch (err) {
2526 console.error("Failed to fetch product:", err)
2527 setError("Failed to load product. Please try again.")
2528 } finally {
2529 setLoading(false)
2530 }
2531 }, [id, selectedRegion])
2532
2533 useEffect(() => {
2534 if (id && selectedRegion) {
2535 fetchProduct()
2536 }
2537 }, [id, selectedRegion, fetchProduct])
2538
2539 // Update screen title immediately if passed as param, or when product is loaded
2540 useEffect(() => {
2541 const productTitle = title || product?.title
2542 if (productTitle) {
2543 navigation.setOptions({
2544 title: productTitle,
2545 })
2546 }
2547 }, [title, product, navigation])
2548
2549 // TODO select variant based on selected options
2550 ```
2551
2552 The `fetchProduct` function retrieves product details from the Medusa backend using the product ID. The region ID is passed as a query parameter to get prices specific to the selected region.
2553
2554 The `selectedOptions` state is initialized with the option values of the product's first variant.
2555
2556 Next, you'll implement the logic to select the appropriate product variant based on the currently selected options. Replace the `// TODO select variant based on selected options` comment with the following:
2557
2558 export const productDetailVariantHighlights = [
2559 ["2", "selectedVariant", "The product variant that matches the currently selected options."],
2560 ["20", "shouldShowOptions", "Whether to show the options UI."],
2561 ["29", "images", "Array of image URLs for the product."],
2562 ]
2563
2564 ```tsx title="app/(drawer)/(tabs)/(home)/product/[id].tsx" highlights={productDetailVariantHighlights}
2565 // Compute selected variant based on selected options
2566 const selectedVariant = useMemo(() => {
2567 if (
2568 !product?.variants ||
2569 !product.options ||
2570 Object.keys(selectedOptions).length !== product.options?.length
2571 ) {
2572 return
2573 }
2574
2575 return product.variants.find((variant) =>
2576 variant.options?.every(
2577 (optionValue) => optionValue.value === selectedOptions[optionValue.option_id!]
2578 )
2579 )
2580 }, [selectedOptions, product])
2581
2582 // Check if we should show options UI
2583 // Hide if there's only one option with one value (or all options have only one value each)
2584 const shouldShowOptions = useMemo(() => {
2585 if (!product?.options || product.options.length === 0) {
2586 return false
2587 }
2588 // Show options only if at least one option has more than one value
2589 return product.options.some((option) => (option.values?.length ?? 0) > 1)
2590 }, [product])
2591
2592 // Get all images from product
2593 const images = useMemo(() => {
2594 const productImages = product?.images?.map((img) => img.url).filter(Boolean) || []
2595 // If no images, use thumbnail or fallback
2596 if (productImages.length === 0 && product?.thumbnail) {
2597 return [product.thumbnail]
2598 }
2599 return productImages.length > 0 ? productImages : []
2600 }, [product])
2601
2602 // TODO handle add to cart
2603 ```
2604
2605 You define the following memoized values:
2606
2607 - `selectedVariant`: The product variant that matches the currently selected options.
2608 - `shouldShowOptions`: A boolean indicating whether to show the options UI. The options UI is hidden if there's a single option with a single value.
2609 - `images`: An array of image URLs for the product, falling back to the thumbnail if no images are available.
2610
2611 Next, you'll implement the logic to handle adding the selected product variant to the cart. Replace the `// TODO handle add to cart` comment with the following:
2612
2613 ```tsx title="app/(drawer)/(tabs)/(home)/product/[id].tsx"
2614 const handleAddToCart = async () => {
2615 if (!selectedVariant) {
2616 setToastMessage(shouldShowOptions ? "Please select all options" : "Variant not available")
2617 setToastVisible(true)
2618 return
2619 }
2620
2621 try {
2622 setAddingToCart(true)
2623 await addToCart(selectedVariant.id, quantity)
2624 setToastMessage("Product added to cart!")
2625 setToastVisible(true)
2626 } catch {
2627 setToastMessage("Failed to add product to cart")
2628 setToastVisible(true)
2629 } finally {
2630 setAddingToCart(false)
2631 }
2632 }
2633
2634 // TODO render UI
2635 ```
2636
2637 The `handleAddToCart` function adds the selected variant to the cart using the `addToCart` function from the cart context. It displays appropriate toast messages based on the outcome.
2638
2639 Finally, you'll implement the UI rendering for the product detail screen. Replace the `// TODO render UI` comment with the following:
2640
2641 ```tsx title="app/(drawer)/(tabs)/(home)/product/[id].tsx"
2642 if (loading) {
2643 return <ProductSkeleton />
2644 }
2645
2646 if (error || !product) {
2647 return (
2648 <View style={[styles.centerContainer, { backgroundColor: colors.background }]}>
2649 <Text style={[styles.errorText, { color: colors.text }]}>
2650 {error || "Product not found"}
2651 </Text>
2652 </View>
2653 )
2654 }
2655
2656 // Get price from calculated_price.calculated_amount
2657 const priceAmount = selectedVariant?.calculated_price?.calculated_amount || 0
2658
2659 // Use selected region's currency code
2660 const currencyCode = selectedRegion?.currency_code
2661
2662 // Check if selected variant is in stock
2663 const isInStock = isVariantInStock(selectedVariant)
2664
2665 return (
2666 <ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
2667 <ProductImageSlider images={images} />
2668
2669 <View style={styles.content}>
2670 <Text style={[styles.title, { color: colors.text }]}>{product.title}</Text>
2671
2672 {product.description && (
2673 <Text style={[styles.description, { color: colors.icon }]}>
2674 {product.description}
2675 </Text>
2676 )}
2677
2678 <View style={styles.priceContainer}>
2679 <Text style={[styles.price, { color: colors.tint }]}>
2680 {formatPrice(priceAmount, currencyCode)}
2681 </Text>
2682 {!isInStock && (
2683 <View style={[styles.stockBadge, { backgroundColor: colors.error }]}>
2684 <Text style={styles.outOfStockText}>Out of Stock</Text>
2685 </View>
2686 )}
2687 {isInStock && selectedVariant?.inventory_quantity !== undefined &&
2688 selectedVariant.inventory_quantity! <= 10 &&
2689 selectedVariant.manage_inventory !== false && (
2690 <View style={[styles.stockBadge, { backgroundColor: colors.warning }]}>
2691 <Text style={styles.lowStockText}>
2692 Only {selectedVariant.inventory_quantity} left
2693 </Text>
2694 </View>
2695 )}
2696 </View>
2697
2698 {shouldShowOptions && (
2699 <View style={styles.optionsSection}>
2700 {product.options?.map((option) => (
2701 <View key={option.id} style={styles.optionGroup}>
2702 <Text style={[styles.sectionTitle, { color: colors.text }]}>
2703 {option.title}
2704 </Text>
2705 <View style={styles.optionValues}>
2706 {option.values?.map((optionValue) => {
2707 const isSelected = selectedOptions[option.id!] === optionValue.value
2708 return (
2709 <TouchableOpacity
2710 key={optionValue.id}
2711 style={[
2712 styles.optionButton,
2713 {
2714 backgroundColor: isSelected
2715 ? colors.tint + "20"
2716 : "transparent",
2717 borderColor: isSelected
2718 ? colors.tint
2719 : colors.icon + "30",
2720 },
2721 ]}
2722 onPress={() => {
2723 setSelectedOptions((prev) => ({
2724 ...prev,
2725 [option.id!]: optionValue.value!,
2726 }))
2727 }}
2728 >
2729 <Text
2730 style={[
2731 styles.optionText,
2732 {
2733 color: isSelected ? colors.tint : colors.text,
2734 fontWeight: isSelected ? "600" : "400",
2735 },
2736 ]}
2737 >
2738 {optionValue.value}
2739 </Text>
2740 </TouchableOpacity>
2741 )
2742 })}
2743 </View>
2744 </View>
2745 ))}
2746 </View>
2747 )}
2748
2749 <View style={styles.quantitySection}>
2750 <Text style={[styles.sectionTitle, { color: colors.text }]}>Quantity</Text>
2751 <View style={styles.quantityControls}>
2752 <TouchableOpacity
2753 style={[styles.quantityButton, { borderColor: colors.icon }]}
2754 onPress={() => setQuantity(Math.max(1, quantity - 1))}
2755 >
2756 <Text style={[styles.quantityButtonText, { color: colors.text }]}>-</Text>
2757 </TouchableOpacity>
2758 <Text style={[styles.quantity, { color: colors.text }]}>{quantity}</Text>
2759 <TouchableOpacity
2760 style={[styles.quantityButton, { borderColor: colors.icon }]}
2761 onPress={() => setQuantity(quantity + 1)}
2762 >
2763 <Text style={[styles.quantityButtonText, { color: colors.text }]}>+</Text>
2764 </TouchableOpacity>
2765 </View>
2766 </View>
2767
2768 <Button
2769 title={isInStock ? "Add to Cart" : "Out of Stock"}
2770 onPress={handleAddToCart}
2771 loading={addingToCart}
2772 disabled={!isInStock}
2773 style={styles.addButton}
2774 />
2775 </View>
2776
2777 <Toast
2778 message={toastMessage}
2779 visible={toastVisible}
2780 onHide={() => setToastVisible(false)}
2781 type="success"
2782 />
2783 </ScrollView>
2784 )
2785 ```
2786
2787 You handle three main states:
2788
2789 1. Loading: Displays the `ProductSkeleton` while fetching product details.
2790 2. Error: Displays an error message if fetching fails or the product is not found.
2791 3. Success: Renders the product detail screen with the image slider, title, description, price, stock status, options, quantity selector, and add to cart button.
2792
2793 ### Add Product Detail Screen to Navigation
2794
2795 Finally, you'll add the product detail screen to the home stack navigator.
2796
2797 In `app/(drawer)/(tabs)/(home)/_layout.tsx`, replace the `TODO add product details screen` comment with the following:
2798
2799 ```tsx title="app/(drawer)/(tabs)/(home)/_layout.tsx"
2800 <Stack.Screen
2801 name="product/[id]"
2802 options={{
2803 title: "Product Details",
2804 presentation: "card",
2805 headerBackButtonDisplayMode: "minimal",
2806 }}
2807 />
2808 ```
2809
2810 A new screen is added to the stack navigator for the product detail screen, allowing users to navigate between the home screen and the product detail screen seamlessly.
2811
2812 ### Test Product Detail Screen
2813
2814 To test out the product detail screen, run your Medusa application and Expo app.
2815
2816 Then, in the home screen, click on a product to view its details. This will open the product detail screen where you can view its images, select options, adjust quantity, and add it to the cart.
2817
2818 ![Product Detail Screen](https://res.cloudinary.com/dza7lstvk/image/upload/v1762417976/Medusa%20Resources/CleanShot_2025-11-06_at_10.29.04_2x_girdxx.png)
2819
2820 You can try adding a product to the cart and see the toast notification confirming the action. You'll implement the cart screen in the next step.
2821
2822 ---
2823
2824 ## Step 10: Create Cart Screen
2825
2826 In this step, you'll create a cart screen where users can view the items they've added to their cart, adjust quantities, and proceed to checkout.
2827
2828 You'll create the necessary components and utilities first, then implement the cart screen and add it to the navigation.
2829
2830 ### Add Cart Item Component
2831
2832 First, you'll create a cart item component to display individual items in the cart.
2833
2834 Create the file `components/cart-item.tsx` with the following content:
2835
2836 ```tsx title="components/cart-item.tsx" collapsibleLines="72-137" expandButtonLabel="Show Styles"
2837 import { IconSymbol } from "@/components/ui/icon-symbol"
2838 import { Colors } from "@/constants/theme"
2839 import { useColorScheme } from "@/hooks/use-color-scheme"
2840 import { formatPrice } from "@/lib/format-price"
2841 import type { HttpTypes } from "@medusajs/types"
2842 import { Image } from "expo-image"
2843 import React from "react"
2844 import { StyleSheet, Text, TouchableOpacity, View } from "react-native"
2845
2846 interface CartItemProps {
2847 item: HttpTypes.StoreCartLineItem;
2848 currencyCode?: string;
2849 onUpdateQuantity: (quantity: number) => void;
2850 onRemove: () => void;
2851 }
2852
2853 export const CartItem = React.memo(function CartItem({ item, currencyCode, onUpdateQuantity, onRemove }: CartItemProps) {
2854 const colorScheme = useColorScheme()
2855 const colors = Colors[colorScheme ?? "light"]
2856
2857 const thumbnail = item.thumbnail || item.variant?.product?.thumbnail
2858 const total = item.subtotal || 0
2859
2860 return (
2861 <View style={[styles.container, { borderBottomColor: colors.icon + "30" }]}>
2862 <Image
2863 source={{ uri: thumbnail || "https://placehold.co/80" }}
2864 style={[styles.image, { backgroundColor: colors.imagePlaceholder }]}
2865 contentFit="cover"
2866 />
2867 <View style={styles.content}>
2868 <View style={styles.info}>
2869 <Text style={[styles.title, { color: colors.text }]} numberOfLines={2}>
2870 {item.product_title || item.title}
2871 </Text>
2872 {item.variant_title && (
2873 <Text style={[styles.variant, { color: colors.icon }]}>
2874 {item.variant_title}
2875 </Text>
2876 )}
2877 <Text style={[styles.price, { color: colors.text }]}>
2878 {formatPrice(total, currencyCode)}
2879 </Text>
2880 </View>
2881 <View style={styles.actions}>
2882 <View style={styles.quantityContainer}>
2883 <TouchableOpacity
2884 style={[styles.quantityButton, { borderColor: colors.icon }]}
2885 onPress={() => onUpdateQuantity(Math.max(1, item.quantity - 1))}
2886 >
2887 <Text style={[styles.quantityButtonText, { color: colors.text }]}>-</Text>
2888 </TouchableOpacity>
2889 <Text style={[styles.quantity, { color: colors.text }]}>
2890 {item.quantity}
2891 </Text>
2892 <TouchableOpacity
2893 style={[styles.quantityButton, { borderColor: colors.icon }]}
2894 onPress={() => onUpdateQuantity(item.quantity + 1)}
2895 >
2896 <Text style={[styles.quantityButtonText, { color: colors.text }]}>+</Text>
2897 </TouchableOpacity>
2898 </View>
2899 <TouchableOpacity onPress={onRemove} style={styles.removeButton}>
2900 <IconSymbol size={20} name="trash" color={colors.text} />
2901 </TouchableOpacity>
2902 </View>
2903 </View>
2904 </View>
2905 )
2906 })
2907
2908 const styles = StyleSheet.create({
2909 container: {
2910 flexDirection: "row",
2911 padding: 16,
2912 borderBottomWidth: 1,
2913 },
2914 image: {
2915 width: 80,
2916 height: 80,
2917 borderRadius: 8,
2918 },
2919 content: {
2920 flex: 1,
2921 marginLeft: 12,
2922 justifyContent: "space-between",
2923 },
2924 info: {
2925 flex: 1,
2926 },
2927 title: {
2928 fontSize: 14,
2929 fontWeight: "600",
2930 marginBottom: 4,
2931 },
2932 variant: {
2933 fontSize: 12,
2934 marginBottom: 4,
2935 },
2936 price: {
2937 fontSize: 14,
2938 fontWeight: "700",
2939 marginTop: 4,
2940 },
2941 actions: {
2942 flexDirection: "row",
2943 alignItems: "center",
2944 justifyContent: "space-between",
2945 marginTop: 8,
2946 },
2947 quantityContainer: {
2948 flexDirection: "row",
2949 alignItems: "center",
2950 },
2951 quantityButton: {
2952 width: 28,
2953 height: 28,
2954 borderRadius: 14,
2955 borderWidth: 1,
2956 alignItems: "center",
2957 justifyContent: "center",
2958 },
2959 quantityButtonText: {
2960 fontSize: 16,
2961 fontWeight: "600",
2962 },
2963 quantity: {
2964 marginHorizontal: 12,
2965 fontSize: 14,
2966 fontWeight: "600",
2967 minWidth: 20,
2968 textAlign: "center",
2969 },
2970 removeButton: {
2971 padding: 4,
2972 },
2973 })
2974 ```
2975
2976 The `CartItem` component receives the following props:
2977
2978 - `item`: The cart line item to display.
2979 - `currencyCode`: The currency code for formatting prices.
2980 - `onUpdateQuantity`: Callback to update the quantity of the item.
2981 - `onRemove`: Callback to remove the item from the cart.
2982
2983 In the component, you display the item's image, title, variant name, and price. You also provide buttons to adjust the quantity and remove the item from the cart.
2984
2985 ### Add Cart Screen
2986
2987 Next, you'll implement the cart screen where users can view and manage their cart items.
2988
2989 As mentioned before, you'll have a tab for the cart screen. So, to create the cart screen, create the file `app/(drawer)/(tabs)/(cart)/index.tsx` with the following content:
2990
2991 ```tsx title="app/(drawer)/(tabs)/(cart)/index.tsx" collapsibleLines="99-158" expandButtonLabel="Show Styles"
2992 import { CartItem } from "@/components/cart-item"
2993 import { Loading } from "@/components/loading"
2994 import { Button } from "@/components/ui/button"
2995 import { Colors } from "@/constants/theme"
2996 import { useCart } from "@/context/cart-context"
2997 import { useColorScheme } from "@/hooks/use-color-scheme"
2998 import { formatPrice } from "@/lib/format-price"
2999 import { useRouter } from "expo-router"
3000 import React from "react"
3001 import { FlatList, StyleSheet, Text, View } from "react-native"
3002
3003 export default function CartScreen() {
3004 const colorScheme = useColorScheme()
3005 const colors = Colors[colorScheme ?? "light"]
3006 const router = useRouter()
3007 const { cart, updateItemQuantity, removeItem, loading } = useCart()
3008
3009 const isEmpty = !cart?.items || cart.items.length === 0
3010
3011 if (loading && !cart) {
3012 return <Loading message="Loading cart..." />
3013 }
3014
3015 if (isEmpty) {
3016 return (
3017 <View style={[styles.emptyContainer, { backgroundColor: colors.background }]}>
3018 <Text style={[styles.emptyTitle, { color: colors.text }]}>Your cart is empty</Text>
3019 <Text style={[styles.emptyText, { color: colors.icon }]}>
3020 Add some products to get started
3021 </Text>
3022 <Button
3023 title="Browse Products"
3024 onPress={() => router.push("/")}
3025 style={styles.browseButton}
3026 />
3027 </View>
3028 )
3029 }
3030
3031 return (
3032 <View style={[styles.container, { backgroundColor: colors.background }]}>
3033 <FlatList
3034 data={cart.items}
3035 keyExtractor={(item) => item.id}
3036 renderItem={({ item }) => (
3037 <CartItem
3038 item={item}
3039 currencyCode={cart.currency_code}
3040 onUpdateQuantity={(quantity) => updateItemQuantity(item.id, quantity)}
3041 onRemove={() => removeItem(item.id)}
3042 />
3043 )}
3044 contentContainerStyle={styles.listContent}
3045 />
3046
3047 <View style={[styles.footer, { backgroundColor: colors.background, borderTopColor: colors.icon + "30" }]}>
3048 <View style={styles.totals}>
3049 <View style={styles.totalRow}>
3050 <Text style={[styles.totalLabel, { color: colors.text }]}>Subtotal</Text>
3051 <Text style={[styles.totalValue, { color: colors.text }]}>
3052 {formatPrice(cart.item_subtotal, cart.currency_code)}
3053 </Text>
3054 </View>
3055 {cart.tax_total !== undefined && cart.tax_total > 0 && (
3056 <View style={styles.totalRow}>
3057 <Text style={[styles.totalLabel, { color: colors.text }]}>Tax</Text>
3058 <Text style={[styles.totalValue, { color: colors.text }]}>
3059 {formatPrice(cart.tax_total, cart.currency_code)}
3060 </Text>
3061 </View>
3062 )}
3063 {cart.shipping_total !== undefined && cart.shipping_total > 0 && (
3064 <View style={styles.totalRow}>
3065 <Text style={[styles.totalLabel, { color: colors.text }]}>Shipping</Text>
3066 <Text style={[styles.totalValue, { color: colors.text }]}>
3067 {formatPrice(cart.shipping_total, cart.currency_code)}
3068 </Text>
3069 </View>
3070 )}
3071 <View style={[styles.totalRow, styles.grandTotalRow, { borderTopColor: colors.border }]}>
3072 <Text style={[styles.grandTotalLabel, { color: colors.text }]}>Total</Text>
3073 <Text style={[styles.grandTotalValue, { color: colors.tint }]}>
3074 {formatPrice(cart.total, cart.currency_code)}
3075 </Text>
3076 </View>
3077 </View>
3078 <Button
3079 title="Proceed to Checkout"
3080 onPress={() => {
3081 // TODO navigate to checkout screen
3082 }}
3083 loading={loading}
3084 />
3085 </View>
3086 </View>
3087 )
3088 }
3089
3090 const styles = StyleSheet.create({
3091 container: {
3092 flex: 1,
3093 },
3094 emptyContainer: {
3095 flex: 1,
3096 justifyContent: "center",
3097 alignItems: "center",
3098 padding: 40,
3099 },
3100 emptyTitle: {
3101 fontSize: 24,
3102 fontWeight: "700",
3103 marginBottom: 12,
3104 },
3105 emptyText: {
3106 fontSize: 16,
3107 textAlign: "center",
3108 marginBottom: 32,
3109 },
3110 browseButton: {
3111 minWidth: 200,
3112 },
3113 listContent: {
3114 paddingBottom: 20,
3115 },
3116 footer: {
3117 padding: 16,
3118 borderTopWidth: 1,
3119 },
3120 totals: {
3121 marginBottom: 20,
3122 },
3123 totalRow: {
3124 flexDirection: "row",
3125 justifyContent: "space-between",
3126 alignItems: "center",
3127 marginBottom: 12,
3128 },
3129 totalLabel: {
3130 fontSize: 14,
3131 },
3132 totalValue: {
3133 fontSize: 14,
3134 fontWeight: "500",
3135 },
3136 grandTotalRow: {
3137 marginTop: 8,
3138 paddingTop: 12,
3139 borderTopWidth: 1,
3140 },
3141 grandTotalLabel: {
3142 fontSize: 18,
3143 fontWeight: "700",
3144 },
3145 grandTotalValue: {
3146 fontSize: 20,
3147 fontWeight: "700",
3148 },
3149 })
3150 ```
3151
3152 You define the `CartScreen` component that uses the `useCart` hook to access the cart state and actions. It handles three main states:
3153
3154 - Loading: Displays a loading indicator while fetching the cart.
3155 - Empty Cart: Displays a message and a button to browse products if the cart is empty.
3156 - Cart with Items: Renders a list of cart items using the `CartItem` component, along with cart totals.
3157
3158 You also provide a button to proceed to checkout. Right now, the button does nothing. You'll change it to navigate to the checkout screen later.
3159
3160 Next, you'll add stack navigation for the cart screen.
3161
3162 Create the file `app/(drawer)/(tabs)/(cart)/_layout.tsx` with the following content:
3163
3164 ```tsx title="app/(drawer)/(tabs)/(cart)/_layout.tsx"
3165 import { useColorScheme } from "@/hooks/use-color-scheme"
3166 import { DrawerActions } from "@react-navigation/native"
3167 import { Stack, useNavigation } from "expo-router"
3168 import React from "react"
3169 import { TouchableOpacity } from "react-native"
3170
3171 import { IconSymbol } from "@/components/ui/icon-symbol"
3172 import { Colors } from "@/constants/theme"
3173
3174 export default function CartStackLayout() {
3175 const colorScheme = useColorScheme()
3176 const navigation = useNavigation()
3177 const colors = Colors[colorScheme ?? "light"]
3178
3179 return (
3180 <Stack
3181 screenOptions={{
3182 headerShown: true,
3183 }}
3184 >
3185 <Stack.Screen
3186 name="index"
3187 options={{
3188 title: "Cart",
3189 headerLeft: () => (
3190 <TouchableOpacity
3191 onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
3192 style={{ height: 36, width: 36, display: "flex", alignItems: "center", justifyContent: "center" }}
3193 >
3194 <IconSymbol size={28} name="line.3.horizontal" color={colors.icon} />
3195 </TouchableOpacity>
3196 ),
3197 }}
3198 />
3199 </Stack>
3200 )
3201 }
3202 ```
3203
3204 You show the cart screen with a header that includes a button to open the drawer navigation.
3205
3206 ### Add Cart Tab to Navigation
3207
3208 Finally, you'll add the cart tab to the main tab navigator.
3209
3210 In `app/(drawer)/(tabs)/_layout.tsx`, add the following import at the top of the file:
3211
3212 ```tsx title="app/(drawer)/(tabs)/_layout.tsx"
3213 import { useCart } from "@/context/cart-context"
3214 ```
3215
3216 Then, in the `TabLayout` component, add the following before the `return` statement:
3217
3218 ```tsx title="app/(drawer)/(tabs)/_layout.tsx"
3219 const { cart } = useCart()
3220
3221 const itemCount = cart?.items?.length || 0
3222 ```
3223
3224 You access the cart from the cart context to get the number of items in the cart.
3225
3226 Finally, replace the `// TODO add cart tab` comment in the `return` statement with the following:
3227
3228 ```tsx title="app/(drawer)/(tabs)/_layout.tsx"
3229 <Tabs.Screen
3230 name="(cart)"
3231 options={{
3232 title: "Cart",
3233 tabBarIcon: ({ color }) => <IconSymbol size={28} name="cart.fill" color={color} />,
3234 tabBarBadge: itemCount > 0 ? itemCount : undefined,
3235 tabBarBadgeStyle: {
3236 backgroundColor: Colors[colorScheme ?? "light"].tint,
3237 },
3238 headerShown: false, // Let the cart stack manage its own headers
3239 }}
3240 />
3241 ```
3242
3243 You add a new tab to the tab navigator for the cart screen. The tab displays a badge with the number of items in the cart.
3244
3245 ### Test Cart Screen
3246
3247 To test out the cart screen, run your Medusa application and Expo app.
3248
3249 Then, add some products to your cart from the product detail screen. You can open the cart by clicking its tab in the bottom navigation.
3250
3251 ![Cart screen with items in it](https://res.cloudinary.com/dza7lstvk/image/upload/v1762358342/Medusa%20Resources/CleanShot_2025-11-05_at_17.58.18_2x_w5gmly.png)
3252
3253 You can update an item's quantity or remove an item, and the cart will be updated accordingly.
3254
3255 ---
3256
3257 ## Step 11: Create Checkout Screen
3258
3259 In this step, you'll create a checkout screen where users enter their address, choose shipping and payment methods, and place their order.
3260
3261 The checkout screen will have three steps:
3262
3263 1. Delivery: Enter shipping and billing addresses.
3264 2. Shipping: Choose a shipping method.
3265 3. Payment: Choose a payment method.
3266
3267 You'll implement first the three steps components, including their components and utilities, then the main checkout screen and navigation.
3268
3269 ### Add Address Form Component
3270
3271 First, you'll create an address form component to collect shipping and billing addresses.
3272
3273 Create the file `components/checkout/address-form.tsx` with the following content:
3274
3275 ```tsx title="components/checkout/address-form.tsx" collapsibleLines="241-297" expandButtonLabel="Show Styles"
3276 import { IconSymbol } from "@/components/ui/icon-symbol"
3277 import { Colors } from "@/constants/theme"
3278 import { useColorScheme } from "@/hooks/use-color-scheme"
3279 import type { HttpTypes } from "@medusajs/types"
3280 import { Picker } from "@react-native-picker/picker"
3281 import React, { useRef, useState } from "react"
3282 import {
3283 Modal,
3284 Platform,
3285 StyleSheet,
3286 Text,
3287 TextInput,
3288 TouchableOpacity,
3289 View,
3290 } from "react-native"
3291
3292 interface AddressFormProps {
3293 firstName: string;
3294 lastName: string;
3295 address: string;
3296 city: string;
3297 postalCode: string;
3298 countryCode: string;
3299 phone: string;
3300 countries: HttpTypes.StoreRegionCountry[];
3301 onFirstNameChange: (value: string) => void;
3302 onLastNameChange: (value: string) => void;
3303 onAddressChange: (value: string) => void;
3304 onCityChange: (value: string) => void;
3305 onPostalCodeChange: (value: string) => void;
3306 onCountryCodeChange: (value: string) => void;
3307 onPhoneChange: (value: string) => void;
3308 }
3309
3310 export function AddressForm({
3311 firstName,
3312 lastName,
3313 address,
3314 city,
3315 postalCode,
3316 countryCode,
3317 phone,
3318 countries,
3319 onFirstNameChange,
3320 onLastNameChange,
3321 onAddressChange,
3322 onCityChange,
3323 onPostalCodeChange,
3324 onCountryCodeChange,
3325 onPhoneChange,
3326 }: AddressFormProps) {
3327 const colorScheme = useColorScheme()
3328 const colors = Colors[colorScheme ?? "light"]
3329 const [showPicker, setShowPicker] = useState(false)
3330 const [tempCountryCode, setTempCountryCode] = useState(countryCode)
3331
3332 // Create refs for each input field
3333 const lastNameRef = useRef<TextInput>(null)
3334 const addressRef = useRef<TextInput>(null)
3335 const cityRef = useRef<TextInput>(null)
3336 const postalCodeRef = useRef<TextInput>(null)
3337 const phoneRef = useRef<TextInput>(null)
3338
3339 const selectedCountry = countries.find(
3340 (c) => (c.iso_2 || c.id) === countryCode
3341 )
3342 const selectedCountryName = selectedCountry
3343 ? selectedCountry.display_name || selectedCountry.name || selectedCountry.iso_2 || selectedCountry.id
3344 : "Select Country"
3345
3346 const handleDone = () => {
3347 onCountryCodeChange(tempCountryCode)
3348 setShowPicker(false)
3349 // Focus phone field after country selection
3350 setTimeout(() => phoneRef.current?.focus(), 100)
3351 }
3352
3353 const handleCancel = () => {
3354 setTempCountryCode(countryCode)
3355 setShowPicker(false)
3356 }
3357
3358 return (
3359 <>
3360 <View style={styles.row}>
3361 <TextInput
3362 style={[
3363 styles.input,
3364 styles.halfInput,
3365 { color: colors.text, borderColor: colors.icon + "30" },
3366 ]}
3367 placeholder="First Name"
3368 placeholderTextColor={colors.icon}
3369 value={firstName}
3370 onChangeText={onFirstNameChange}
3371 returnKeyType="next"
3372 onSubmitEditing={() => lastNameRef.current?.focus()}
3373 />
3374 <TextInput
3375 ref={lastNameRef}
3376 style={[
3377 styles.input,
3378 styles.halfInput,
3379 { color: colors.text, borderColor: colors.icon + "30" },
3380 ]}
3381 placeholder="Last Name"
3382 placeholderTextColor={colors.icon}
3383 value={lastName}
3384 onChangeText={onLastNameChange}
3385 returnKeyType="next"
3386 onSubmitEditing={() => addressRef.current?.focus()}
3387 />
3388 </View>
3389
3390 <TextInput
3391 ref={addressRef}
3392 style={[styles.input, { color: colors.text, borderColor: colors.icon + "30" }]}
3393 placeholder="Address"
3394 placeholderTextColor={colors.icon}
3395 value={address}
3396 onChangeText={onAddressChange}
3397 returnKeyType="next"
3398 onSubmitEditing={() => cityRef.current?.focus()}
3399 />
3400
3401 <View style={styles.row}>
3402 <TextInput
3403 ref={cityRef}
3404 style={[
3405 styles.input,
3406 styles.halfInput,
3407 { color: colors.text, borderColor: colors.icon + "30" },
3408 ]}
3409 placeholder="City"
3410 placeholderTextColor={colors.icon}
3411 value={city}
3412 onChangeText={onCityChange}
3413 returnKeyType="next"
3414 onSubmitEditing={() => postalCodeRef.current?.focus()}
3415 />
3416 <TextInput
3417 ref={postalCodeRef}
3418 style={[
3419 styles.input,
3420 styles.halfInput,
3421 { color: colors.text, borderColor: colors.icon + "30" },
3422 ]}
3423 placeholder="Postal Code"
3424 placeholderTextColor={colors.icon}
3425 value={postalCode}
3426 onChangeText={onPostalCodeChange}
3427 returnKeyType="next"
3428 onSubmitEditing={() => {
3429 setTempCountryCode(countryCode)
3430 setShowPicker(true)
3431 }}
3432 />
3433 </View>
3434
3435 <TouchableOpacity
3436 style={[
3437 styles.input,
3438 styles.pickerButton,
3439 { borderColor: colors.icon + "30" },
3440 ]}
3441 onPress={() => {
3442 setTempCountryCode(countryCode)
3443 setShowPicker(true)
3444 }}
3445 >
3446 <Text style={[styles.pickerButtonText, { color: countryCode ? colors.text : colors.icon }]}>
3447 {selectedCountryName}
3448 </Text>
3449 <IconSymbol size={20} name="chevron.down" color={colors.icon} />
3450 </TouchableOpacity>
3451
3452 <Modal
3453 visible={showPicker}
3454 transparent={true}
3455 animationType="none"
3456 onRequestClose={handleCancel}
3457 >
3458 <TouchableOpacity
3459 style={styles.modalOverlay}
3460 activeOpacity={1}
3461 onPress={handleCancel}
3462 >
3463 <TouchableOpacity
3464 activeOpacity={1}
3465 style={[styles.modalContent, { backgroundColor: colors.background }]}
3466 onPress={(e) => e.stopPropagation()}
3467 >
3468 <View style={[styles.modalHeader, { borderBottomColor: colors.icon + "30" }]}>
3469 <TouchableOpacity onPress={handleCancel}>
3470 <Text style={[styles.modalButton, { color: colors.tint }]}>Cancel</Text>
3471 </TouchableOpacity>
3472 <Text style={[styles.modalTitle, { color: colors.text }]}>Select Country</Text>
3473 <TouchableOpacity onPress={handleDone}>
3474 <Text style={[styles.modalButton, { color: colors.tint }]}>Done</Text>
3475 </TouchableOpacity>
3476 </View>
3477 <Picker
3478 selectedValue={tempCountryCode}
3479 onValueChange={(value) => {
3480 setTempCountryCode(value)
3481 if (Platform.OS === "android") {
3482 onCountryCodeChange(value)
3483 setShowPicker(false)
3484 // Focus phone field after country selection on Android
3485 setTimeout(() => phoneRef.current?.focus(), 100)
3486 }
3487 }}
3488 style={[styles.picker, Platform.OS === "android" && { color: colors.text }]}
3489 itemStyle={Platform.OS === "ios" ? styles.pickerItemIOS : undefined}
3490 >
3491 <Picker.Item label="Select Country" value="" enabled={false} />
3492 {countries.map((country) => {
3493 const code = country.iso_2 || country.id
3494 const name = country.display_name || country.name || country.iso_2 || country.id
3495 return <Picker.Item key={code} label={name} value={code} />
3496 })}
3497 </Picker>
3498 </TouchableOpacity>
3499 </TouchableOpacity>
3500 </Modal>
3501
3502 <TextInput
3503 ref={phoneRef}
3504 style={[styles.input, { color: colors.text, borderColor: colors.icon + "30" }]}
3505 placeholder="Phone Number"
3506 placeholderTextColor={colors.icon}
3507 value={phone}
3508 onChangeText={onPhoneChange}
3509 keyboardType="phone-pad"
3510 returnKeyType="done"
3511 />
3512 </>
3513 )
3514 }
3515
3516 const styles = StyleSheet.create({
3517 input: {
3518 borderWidth: 1,
3519 borderRadius: 8,
3520 padding: 12,
3521 fontSize: 16,
3522 marginBottom: 12,
3523 },
3524 row: {
3525 flexDirection: "row",
3526 gap: 12,
3527 },
3528 halfInput: {
3529 flex: 1,
3530 },
3531 pickerButton: {
3532 flexDirection: "row",
3533 justifyContent: "space-between",
3534 alignItems: "center",
3535 },
3536 pickerButtonText: {
3537 fontSize: 16,
3538 flex: 1,
3539 },
3540 modalOverlay: {
3541 flex: 1,
3542 backgroundColor: "rgba(0, 0, 0, 0.5)",
3543 justifyContent: "flex-end",
3544 },
3545 modalContent: {
3546 borderTopLeftRadius: 20,
3547 borderTopRightRadius: 20,
3548 maxHeight: "50%",
3549 },
3550 modalHeader: {
3551 flexDirection: "row",
3552 justifyContent: "space-between",
3553 alignItems: "center",
3554 padding: 16,
3555 borderBottomWidth: 1,
3556 },
3557 modalTitle: {
3558 fontSize: 18,
3559 fontWeight: "600",
3560 },
3561 modalButton: {
3562 fontSize: 16,
3563 fontWeight: "600",
3564 },
3565 picker: {
3566 width: "100%",
3567 height: Platform.OS === "ios" ? 250 : 48,
3568 },
3569 pickerItemIOS: {
3570 height: 200,
3571 },
3572 })
3573 ```
3574
3575 The `AddressForm` component receives various props for the address fields and their change handlers. It also receives a list of countries to populate the country picker.
3576
3577 The component renders input fields for the address and a modal picker for selecting the country. It handles input focus and country selection appropriately.
3578
3579 ### Add Delivery Step Component
3580
3581 Next, you'll create the delivery step component for the checkout process. It will use the `AddressForm` component to collect shipping and billing addresses.
3582
3583 Create the file `components/checkout/delivery-step.tsx` with the following content:
3584
3585 ```tsx title="components/checkout/delivery-step.tsx" collapsibleLines="185-232" expandButtonLabel="Show Styles"
3586 import { AddressForm } from "@/components/checkout/address-form"
3587 import { Button } from "@/components/ui/button"
3588 import { Colors } from "@/constants/theme"
3589 import { useRegion } from "@/context/region-context"
3590 import { useColorScheme } from "@/hooks/use-color-scheme"
3591 import React, { useEffect, useRef, useState } from "react"
3592 import {
3593 Keyboard,
3594 KeyboardAvoidingView,
3595 Platform,
3596 ScrollView,
3597 StyleSheet,
3598 Switch,
3599 Text,
3600 TextInput,
3601 View,
3602 } from "react-native"
3603
3604 interface Address {
3605 firstName: string;
3606 lastName: string;
3607 address: string;
3608 city: string;
3609 postalCode: string;
3610 countryCode: string;
3611 phone: string;
3612 }
3613
3614 interface DeliveryStepProps {
3615 email: string;
3616 shippingAddress: Address;
3617 billingAddress: Address;
3618 useSameForBilling: boolean;
3619 loading: boolean;
3620 onEmailChange: (value: string) => void;
3621 onShippingAddressChange: (field: keyof Address, value: string) => void;
3622 onBillingAddressChange: (field: keyof Address, value: string) => void;
3623 onUseSameForBillingChange: (value: boolean) => void;
3624 onNext: () => void;
3625 }
3626
3627 export function DeliveryStep({
3628 email,
3629 shippingAddress,
3630 billingAddress,
3631 useSameForBilling,
3632 loading,
3633 onEmailChange,
3634 onShippingAddressChange,
3635 onBillingAddressChange,
3636 onUseSameForBillingChange,
3637 onNext,
3638 }: DeliveryStepProps) {
3639 const colorScheme = useColorScheme()
3640 const colors = Colors[colorScheme ?? "light"]
3641 const { selectedRegion } = useRegion()
3642 const scrollViewRef = useRef<ScrollView>(null)
3643 const [isKeyboardVisible, setKeyboardVisible] = useState(false)
3644
3645 const countries = selectedRegion?.countries || []
3646
3647 useEffect(() => {
3648 const keyboardWillShowListener = Keyboard.addListener(
3649 Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow",
3650 () => setKeyboardVisible(true)
3651 )
3652 const keyboardWillHideListener = Keyboard.addListener(
3653 Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide",
3654 () => setKeyboardVisible(false)
3655 )
3656
3657 return () => {
3658 keyboardWillShowListener.remove()
3659 keyboardWillHideListener.remove()
3660 }
3661 }, [])
3662
3663 return (
3664 <KeyboardAvoidingView
3665 style={styles.container}
3666 behavior={Platform.OS === "ios" ? "padding" : "height"}
3667 keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0}
3668 >
3669 <ScrollView
3670 ref={scrollViewRef}
3671 style={styles.scrollView}
3672 contentContainerStyle={[
3673 styles.scrollContent,
3674 isKeyboardVisible && styles.scrollContentKeyboard,
3675 ]}
3676 keyboardShouldPersistTaps="handled"
3677 keyboardDismissMode="on-drag"
3678 showsVerticalScrollIndicator={true}
3679 automaticallyAdjustKeyboardInsets={true}
3680 >
3681 <View style={styles.section}>
3682 <Text style={[styles.sectionTitle, { color: colors.text }]}>
3683 Contact Information
3684 </Text>
3685
3686 <TextInput
3687 style={[styles.input, { color: colors.text, borderColor: colors.icon + "30" }]}
3688 placeholder="Email"
3689 placeholderTextColor={colors.icon}
3690 value={email}
3691 onChangeText={onEmailChange}
3692 keyboardType="email-address"
3693 autoCapitalize="none"
3694 returnKeyType="next"
3695 />
3696
3697 <Text style={[styles.sectionTitle, { color: colors.text, marginTop: 20 }]}>
3698 Shipping Address
3699 </Text>
3700
3701 <AddressForm
3702 firstName={shippingAddress.firstName}
3703 lastName={shippingAddress.lastName}
3704 address={shippingAddress.address}
3705 city={shippingAddress.city}
3706 postalCode={shippingAddress.postalCode}
3707 countryCode={shippingAddress.countryCode}
3708 phone={shippingAddress.phone}
3709 countries={countries}
3710 onFirstNameChange={(value) => onShippingAddressChange("firstName", value)}
3711 onLastNameChange={(value) => onShippingAddressChange("lastName", value)}
3712 onAddressChange={(value) => onShippingAddressChange("address", value)}
3713 onCityChange={(value) => onShippingAddressChange("city", value)}
3714 onPostalCodeChange={(value) => onShippingAddressChange("postalCode", value)}
3715 onCountryCodeChange={(value) => onShippingAddressChange("countryCode", value)}
3716 onPhoneChange={(value) => onShippingAddressChange("phone", value)}
3717 />
3718
3719 <View style={styles.switchContainer}>
3720 <Text style={[styles.switchLabel, { color: colors.text }]}>
3721 Use same address for billing
3722 </Text>
3723 <Switch
3724 value={useSameForBilling}
3725 onValueChange={onUseSameForBillingChange}
3726 />
3727 </View>
3728
3729 {!useSameForBilling && (
3730 <>
3731 <Text style={[styles.sectionTitle, { color: colors.text, marginTop: 20 }]}>
3732 Billing Address
3733 </Text>
3734
3735 <AddressForm
3736 firstName={billingAddress.firstName}
3737 lastName={billingAddress.lastName}
3738 address={billingAddress.address}
3739 city={billingAddress.city}
3740 postalCode={billingAddress.postalCode}
3741 countryCode={billingAddress.countryCode}
3742 phone={billingAddress.phone}
3743 countries={countries}
3744 onFirstNameChange={(value) => onBillingAddressChange("firstName", value)}
3745 onLastNameChange={(value) => onBillingAddressChange("lastName", value)}
3746 onAddressChange={(value) => onBillingAddressChange("address", value)}
3747 onCityChange={(value) => onBillingAddressChange("city", value)}
3748 onPostalCodeChange={(value) => onBillingAddressChange("postalCode", value)}
3749 onCountryCodeChange={(value) => onBillingAddressChange("countryCode", value)}
3750 onPhoneChange={(value) => onBillingAddressChange("phone", value)}
3751 />
3752 </>
3753 )}
3754 </View>
3755
3756 {/* Button moved inside ScrollView for consistent behavior */}
3757 <View style={[styles.buttonContainer, { backgroundColor: colors.background }]}>
3758 <Button
3759 title="Continue"
3760 onPress={onNext}
3761 loading={loading}
3762 style={styles.button}
3763 />
3764 </View>
3765 </ScrollView>
3766 </KeyboardAvoidingView>
3767 )
3768 }
3769
3770 const styles = StyleSheet.create({
3771 container: {
3772 flex: 1,
3773 },
3774 scrollView: {
3775 flex: 1,
3776 },
3777 scrollContent: {
3778 flexGrow: 1,
3779 paddingBottom: 20,
3780 },
3781 scrollContentKeyboard: {
3782 paddingBottom: Platform.OS === "ios" ? 300 : 320,
3783 },
3784 section: {
3785 padding: 20,
3786 },
3787 buttonContainer: {
3788 padding: 20,
3789 paddingTop: 10,
3790 paddingBottom: 30,
3791 },
3792 sectionTitle: {
3793 fontSize: 20,
3794 fontWeight: "700",
3795 marginBottom: 20,
3796 },
3797 input: {
3798 borderWidth: 1,
3799 borderRadius: 8,
3800 padding: 12,
3801 fontSize: 16,
3802 marginBottom: 12,
3803 },
3804 switchContainer: {
3805 flexDirection: "row",
3806 alignItems: "center",
3807 justifyContent: "space-between",
3808 marginVertical: 16,
3809 },
3810 switchLabel: {
3811 fontSize: 16,
3812 flex: 1,
3813 },
3814 button: {
3815 marginTop: 8,
3816 },
3817 })
3818 ```
3819
3820 The `DeliveryStep` component receives the following props:
3821
3822 - `email`: The email address associated with the cart.
3823 - `shippingAddress`: The shipping address details of the cart.
3824 - `billingAddress`: The billing address details of the cart.
3825 - `useSameForBilling`: A boolean indicating whether to use the shipping address for billing.
3826 - `loading`: A boolean indicating whether the form is in a loading state.
3827 - `onEmailChange`: Callback to update the email address.
3828 - `onShippingAddressChange`: Callback to update the shipping address fields.
3829 - `onBillingAddressChange`: Callback to update the billing address fields.
3830 - `onUseSameForBillingChange`: Callback to toggle the use of the same address for billing.
3831 - `onNext`: Callback to proceed to the next step.
3832
3833 The component renders an email input field and uses the `AddressForm` component to collect shipping and billing addresses. A switch is provided to toggle whether to use the same address for billing.
3834
3835 ### Add Shipping Step Component
3836
3837 Next, you'll create the shipping step component for the checkout process. This step allows users to select a shipping method.
3838
3839 Create the file `components/checkout/shipping-step.tsx` with the following content:
3840
3841 ```tsx title="components/checkout/shipping-step.tsx" collapsibleLines="113-165" expandButtonLabel="Show Styles"
3842 import { Loading } from "@/components/loading"
3843 import { Button } from "@/components/ui/button"
3844 import { Colors } from "@/constants/theme"
3845 import { useColorScheme } from "@/hooks/use-color-scheme"
3846 import { formatPrice } from "@/lib/format-price"
3847 import type { HttpTypes } from "@medusajs/types"
3848 import React from "react"
3849 import { StyleSheet, Text, TouchableOpacity, View } from "react-native"
3850
3851 interface ShippingStepProps {
3852 shippingOptions: HttpTypes.StoreCartShippingOption[];
3853 selectedShippingOption: string | null;
3854 currencyCode?: string;
3855 loading: boolean;
3856 onSelectOption: (optionId: string) => void;
3857 onBack: () => void;
3858 onNext: () => void;
3859 }
3860
3861 export function ShippingStep({
3862 shippingOptions,
3863 selectedShippingOption,
3864 currencyCode,
3865 loading,
3866 onSelectOption,
3867 onBack,
3868 onNext,
3869 }: ShippingStepProps) {
3870 const colorScheme = useColorScheme()
3871 const colors = Colors[colorScheme ?? "light"]
3872
3873 return (
3874 <View style={styles.container}>
3875 <View style={styles.contentWrapper}>
3876 <View style={styles.section}>
3877 <Text style={[styles.sectionTitle, { color: colors.text }]}>
3878 Select Shipping Method
3879 </Text>
3880
3881 {loading ? (
3882 <Loading />
3883 ) : shippingOptions.length === 0 ? (
3884 <Text style={[styles.emptyText, { color: colors.icon }]}>
3885 No shipping options available
3886 </Text>
3887 ) : (
3888 shippingOptions.map((option) => (
3889 <TouchableOpacity
3890 key={option.id}
3891 style={[
3892 styles.optionCard,
3893 {
3894 backgroundColor:
3895 selectedShippingOption === option.id
3896 ? colors.tint + "20"
3897 : "transparent",
3898 borderColor:
3899 selectedShippingOption === option.id
3900 ? colors.tint
3901 : colors.icon + "30",
3902 },
3903 ]}
3904 onPress={() => onSelectOption(option.id)}
3905 >
3906 <View style={styles.optionInfo}>
3907 <Text
3908 style={[
3909 styles.optionTitle,
3910 {
3911 color:
3912 selectedShippingOption === option.id
3913 ? colors.tint
3914 : colors.text,
3915 },
3916 ]}
3917 >
3918 {option.name}
3919 </Text>
3920 <Text style={[styles.optionPrice, { color: colors.text }]}>
3921 {formatPrice(option.amount, currencyCode)}
3922 </Text>
3923 </View>
3924 {selectedShippingOption === option.id && (
3925 <Text style={{ color: colors.tint, fontSize: 20 }}>✓</Text>
3926 )}
3927 </TouchableOpacity>
3928 ))
3929 )}
3930 </View>
3931 </View>
3932
3933 <View style={[styles.buttonContainer, { backgroundColor: colors.background, borderTopColor: colors.icon + "30" }]}>
3934 <View style={styles.buttonRow}>
3935 <Button
3936 title="Back"
3937 variant="secondary"
3938 onPress={onBack}
3939 style={styles.halfButton}
3940 />
3941 <Button
3942 title="Continue"
3943 onPress={onNext}
3944 loading={loading}
3945 disabled={!selectedShippingOption}
3946 style={styles.halfButton}
3947 />
3948 </View>
3949 </View>
3950 </View>
3951 )
3952 }
3953
3954 const styles = StyleSheet.create({
3955 container: {
3956 flex: 1,
3957 },
3958 contentWrapper: {
3959 flex: 1,
3960 },
3961 section: {
3962 padding: 20,
3963 },
3964 buttonContainer: {
3965 padding: 20,
3966 paddingBottom: 30,
3967 borderTopWidth: 1,
3968 },
3969 sectionTitle: {
3970 fontSize: 20,
3971 fontWeight: "700",
3972 marginBottom: 20,
3973 },
3974 optionCard: {
3975 flexDirection: "row",
3976 justifyContent: "space-between",
3977 alignItems: "center",
3978 padding: 16,
3979 borderRadius: 8,
3980 borderWidth: 1,
3981 marginBottom: 12,
3982 },
3983 optionInfo: {
3984 flex: 1,
3985 },
3986 optionTitle: {
3987 fontSize: 16,
3988 fontWeight: "600",
3989 marginBottom: 4,
3990 },
3991 optionPrice: {
3992 fontSize: 14,
3993 },
3994 emptyText: {
3995 fontSize: 16,
3996 textAlign: "center",
3997 padding: 20,
3998 },
3999 buttonRow: {
4000 flexDirection: "row",
4001 gap: 12,
4002 },
4003 halfButton: {
4004 flex: 1,
4005 },
4006 })
4007 ```
4008
4009 The `ShippingStep` component receives the following props:
4010
4011 - `shippingOptions`: An array of available shipping options.
4012 - `selectedShippingOption`: The ID of the currently selected shipping option.
4013 - `currencyCode`: The currency code for formatting prices.
4014 - `loading`: A boolean indicating whether the shipping options are being loaded.
4015 - `onSelectOption`: Callback to select a shipping option.
4016 - `onBack`: Callback to go back to the previous step.
4017 - `onNext`: Callback to proceed to the next step.
4018
4019 The component renders a list of shipping options with their names and prices. The selected option is highlighted.
4020
4021 ### Add Payment Provider Utility
4022
4023 Before creating the payment step component, you'll add a utility function that maps payment provider IDs to their display information.
4024
4025 Create the file `lib/payment-providers.ts` with the following content:
4026
4027 ```ts title="lib/payment-providers.ts"
4028 /**
4029 * Information about a payment provider for display purposes
4030 */
4031 export interface PaymentProviderInfo {
4032 icon: string;
4033 title: string;
4034 }
4035
4036 /**
4037 * Get display information for a payment provider based on its ID
4038 * Returns an icon name and formatted title for the payment provider
4039 */
4040 export function getPaymentProviderInfo(providerId: string): PaymentProviderInfo {
4041 switch (providerId) {
4042 case "pp_system_default":
4043 return {
4044 icon: "creditcard",
4045 title: "Manual Payment",
4046 }
4047 default:
4048 return {
4049 icon: "creditcard",
4050 title: providerId.replace("pp_", "").replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()),
4051 }
4052 }
4053 }
4054 ```
4055
4056 The `getPaymentProviderInfo` function takes a payment provider ID and returns an object containing an icon name and a formatted title for display purposes.
4057
4058 The function only handles Medusa's built-in manual payment provider `pp_system_default`. You can expand it later to include more providers that you integrate.
4059
4060 ### Add Payment Step Component
4061
4062 You'll now create the payment step component for the checkout process. This step allows users to select a payment method, and shows the cart's summary before placing the order.
4063
4064 This step will not handle actual payment processing. Instead, it will just allow users to select a payment method and place the order. If you integrate real payment providers later, you'll need to handle their specific payment flows.
4065
4066 Create the file `components/checkout/payment-step.tsx` with the following content:
4067
4068 ```tsx title="components/checkout/payment-step.tsx" collapsibleLines="149-237" expandButtonLabel="Show Styles"
4069 import { Loading } from "@/components/loading"
4070 import { Button } from "@/components/ui/button"
4071 import { IconSymbol } from "@/components/ui/icon-symbol"
4072 import { Colors } from "@/constants/theme"
4073 import { useColorScheme } from "@/hooks/use-color-scheme"
4074 import { formatPrice } from "@/lib/format-price"
4075 import { getPaymentProviderInfo } from "@/lib/payment-providers"
4076 import type { HttpTypes } from "@medusajs/types"
4077 import React from "react"
4078 import { StyleSheet, Text, TouchableOpacity, View } from "react-native"
4079
4080 interface PaymentStepProps {
4081 cart: HttpTypes.StoreCart;
4082 paymentProviders: HttpTypes.StorePaymentProvider[];
4083 selectedPaymentProvider: string | null;
4084 loading: boolean;
4085 onSelectProvider: (providerId: string) => void;
4086 onBack: () => void;
4087 onPlaceOrder: () => void;
4088 }
4089
4090 export function PaymentStep({
4091 cart,
4092 paymentProviders,
4093 selectedPaymentProvider,
4094 loading,
4095 onSelectProvider,
4096 onBack,
4097 onPlaceOrder,
4098 }: PaymentStepProps) {
4099 const colorScheme = useColorScheme()
4100 const colors = Colors[colorScheme ?? "light"]
4101
4102 return (
4103 <View style={styles.container}>
4104 <View style={styles.contentWrapper}>
4105 <View style={styles.section}>
4106 <Text style={[styles.sectionTitle, { color: colors.text }]}>
4107 Select Payment Method
4108 </Text>
4109
4110 {loading ? (
4111 <Loading />
4112 ) : paymentProviders.length === 0 ? (
4113 <Text style={[styles.emptyText, { color: colors.icon }]}>
4114 No payment providers available
4115 </Text>
4116 ) : (
4117 paymentProviders.map((provider) => {
4118 const providerInfo = getPaymentProviderInfo(provider.id)
4119 const isSelected = selectedPaymentProvider === provider.id
4120
4121 return (
4122 <TouchableOpacity
4123 key={provider.id}
4124 style={[
4125 styles.optionCard,
4126 {
4127 backgroundColor: isSelected ? colors.tint + "20" : "transparent",
4128 borderColor: isSelected ? colors.tint : colors.icon + "30",
4129 },
4130 ]}
4131 onPress={() => onSelectProvider(provider.id)}
4132 >
4133 <View style={styles.optionContent}>
4134 <IconSymbol
4135 size={24}
4136 name={providerInfo.icon as any}
4137 color={isSelected ? colors.tint : colors.icon}
4138 />
4139 <Text
4140 style={[
4141 styles.optionTitle,
4142 {
4143 color: isSelected ? colors.tint : colors.text,
4144 },
4145 ]}
4146 >
4147 {providerInfo.title}
4148 </Text>
4149 </View>
4150 {isSelected && (
4151 <Text style={{ color: colors.tint, fontSize: 20 }}>✓</Text>
4152 )}
4153 </TouchableOpacity>
4154 )
4155 })
4156 )}
4157
4158 <View style={[styles.summary, { borderColor: colors.icon + "30" }]}>
4159 <Text style={[styles.summaryTitle, { color: colors.text }]}>
4160 Order Summary
4161 </Text>
4162 <View style={styles.summaryRow}>
4163 <Text style={[styles.summaryLabel, { color: colors.text }]}>Subtotal</Text>
4164 <Text style={[styles.summaryValue, { color: colors.text }]}>
4165 {formatPrice(cart.item_subtotal || 0, cart.currency_code)}
4166 </Text>
4167 </View>
4168 <View style={styles.summaryRow}>
4169 <Text style={[styles.summaryLabel, { color: colors.text }]}>Discount</Text>
4170 <Text style={[styles.summaryValue, { color: colors.text }]}>
4171 {(cart.discount_total || 0) > 0 ? "-" : ""}{formatPrice(cart.discount_total || 0, cart.currency_code)}
4172 </Text>
4173 </View>
4174 <View style={styles.summaryRow}>
4175 <Text style={[styles.summaryLabel, { color: colors.text }]}>Shipping</Text>
4176 <Text style={[styles.summaryValue, { color: colors.text }]}>
4177 {formatPrice(cart.shipping_total || 0, cart.currency_code)}
4178 </Text>
4179 </View>
4180 <View style={styles.summaryRow}>
4181 <Text style={[styles.summaryLabel, { color: colors.text }]}>Tax</Text>
4182 <Text style={[styles.summaryValue, { color: colors.text }]}>
4183 {formatPrice(cart.tax_total || 0, cart.currency_code)}
4184 </Text>
4185 </View>
4186 <View style={[styles.summaryRow, styles.totalRow, { borderTopColor: colors.border }]}>
4187 <Text style={[styles.totalLabel, { color: colors.text }]}>Total</Text>
4188 <Text style={[styles.totalValue, { color: colors.tint }]}>
4189 {formatPrice(cart.total, cart.currency_code)}
4190 </Text>
4191 </View>
4192 </View>
4193 </View>
4194 </View>
4195
4196 <View style={[styles.buttonContainer, { backgroundColor: colors.background, borderTopColor: colors.icon + "30" }]}>
4197 <View style={styles.buttonRow}>
4198 <Button
4199 title="Back"
4200 variant="secondary"
4201 onPress={onBack}
4202 style={styles.halfButton}
4203 />
4204 <Button
4205 title="Place Order"
4206 onPress={onPlaceOrder}
4207 loading={loading}
4208 disabled={!selectedPaymentProvider}
4209 style={styles.halfButton}
4210 />
4211 </View>
4212 </View>
4213 </View>
4214 )
4215 }
4216
4217 const styles = StyleSheet.create({
4218 container: {
4219 flex: 1,
4220 },
4221 contentWrapper: {
4222 flex: 1,
4223 },
4224 section: {
4225 padding: 20,
4226 },
4227 buttonContainer: {
4228 padding: 20,
4229 paddingBottom: 30,
4230 borderTopWidth: 1,
4231 },
4232 sectionTitle: {
4233 fontSize: 20,
4234 fontWeight: "700",
4235 marginBottom: 20,
4236 },
4237 optionCard: {
4238 flexDirection: "row",
4239 justifyContent: "space-between",
4240 alignItems: "center",
4241 padding: 16,
4242 borderRadius: 8,
4243 borderWidth: 1,
4244 marginBottom: 12,
4245 },
4246 optionContent: {
4247 flexDirection: "row",
4248 alignItems: "center",
4249 gap: 12,
4250 flex: 1,
4251 },
4252 optionTitle: {
4253 fontSize: 16,
4254 fontWeight: "600",
4255 },
4256 emptyText: {
4257 fontSize: 16,
4258 textAlign: "center",
4259 padding: 20,
4260 },
4261 summary: {
4262 borderWidth: 1,
4263 borderRadius: 8,
4264 padding: 16,
4265 marginTop: 20,
4266 marginBottom: 20,
4267 },
4268 summaryTitle: {
4269 fontSize: 18,
4270 fontWeight: "700",
4271 marginBottom: 12,
4272 },
4273 summaryRow: {
4274 flexDirection: "row",
4275 justifyContent: "space-between",
4276 marginBottom: 8,
4277 },
4278 summaryLabel: {
4279 fontSize: 14,
4280 },
4281 summaryValue: {
4282 fontSize: 14,
4283 fontWeight: "500",
4284 },
4285 totalRow: {
4286 marginTop: 12,
4287 paddingTop: 12,
4288 borderTopWidth: 1,
4289 },
4290 totalLabel: {
4291 fontSize: 18,
4292 fontWeight: "700",
4293 },
4294 totalValue: {
4295 fontSize: 20,
4296 fontWeight: "700",
4297 },
4298 buttonRow: {
4299 flexDirection: "row",
4300 gap: 12,
4301 },
4302 halfButton: {
4303 flex: 1,
4304 },
4305 })
4306 ```
4307
4308 The `PaymentStep` component receives the following props:
4309
4310 - `cart`: The current cart object containing pricing details.
4311 - `paymentProviders`: An array of available payment providers.
4312 - `selectedPaymentProvider`: The ID of the currently selected payment provider.
4313 - `loading`: A boolean indicating whether the payment providers are being loaded.
4314 - `onSelectProvider`: Callback to select a payment provider.
4315 - `onBack`: Callback to go back to the previous step.
4316 - `onPlaceOrder`: Callback to place the order.
4317
4318 The component renders a list of payment providers with their icons and titles. The selected provider is highlighted.
4319
4320 A summary of the cart's pricing details is displayed, including subtotal, discounts, shipping, tax, and total amount.
4321
4322 ### Add Checkout Screen Component
4323
4324 Finally, you'll create the main checkout screen that manages the multi-step checkout process. It will use the previously created step components to guide users through entering their information, selecting shipping and payment methods, and placing their order.
4325
4326 Create the file `app/checkout.tsx` with the following content:
4327
4328 ```tsx title="app/checkout.tsx" collapsibleLines="55-96" expandButtonLabel="Show Styles"
4329 import { DeliveryStep } from "@/components/checkout/delivery-step"
4330 import { PaymentStep } from "@/components/checkout/payment-step"
4331 import { ShippingStep } from "@/components/checkout/shipping-step"
4332 import { Colors } from "@/constants/theme"
4333 import { useCart } from "@/context/cart-context"
4334 import { useColorScheme } from "@/hooks/use-color-scheme"
4335 import { sdk } from "@/lib/sdk"
4336 import type { HttpTypes } from "@medusajs/types"
4337 import React, { useCallback, useEffect, useState } from "react"
4338 import { Alert, StyleSheet, Text, View } from "react-native"
4339
4340 type CheckoutStep = "delivery" | "shipping" | "payment";
4341
4342 export default function CheckoutScreen() {
4343 const colorScheme = useColorScheme()
4344 const colors = Colors[colorScheme ?? "light"]
4345 const { cart, refreshCart } = useCart()
4346
4347 const [currentStep, setCurrentStep] = useState<CheckoutStep>("delivery")
4348 const [loading, setLoading] = useState(false)
4349
4350 // Contact & Address state
4351 const [email, setEmail] = useState("")
4352 const [shippingAddress, setShippingAddress] = useState({
4353 firstName: "",
4354 lastName: "",
4355 address: "",
4356 city: "",
4357 postalCode: "",
4358 countryCode: "",
4359 phone: "",
4360 })
4361 const [useSameForBilling, setUseSameForBilling] = useState(true)
4362 const [billingAddress, setBillingAddress] = useState({
4363 firstName: "",
4364 lastName: "",
4365 address: "",
4366 city: "",
4367 postalCode: "",
4368 countryCode: "",
4369 phone: "",
4370 })
4371
4372 // Shipping step
4373 const [shippingOptions, setShippingOptions] = useState<HttpTypes.StoreCartShippingOption[]>([])
4374 const [selectedShippingOption, setSelectedShippingOption] = useState<string | null>(null)
4375
4376 // Payment step
4377 const [paymentProviders, setPaymentProviders] = useState<HttpTypes.StorePaymentProvider[]>([])
4378 const [selectedPaymentProvider, setSelectedPaymentProvider] = useState<string | null>(null)
4379
4380 // TODO update state when cart changes
4381 }
4382
4383 const styles = StyleSheet.create({
4384 container: {
4385 flex: 1,
4386 },
4387 centerContainer: {
4388 flex: 1,
4389 justifyContent: "center",
4390 alignItems: "center",
4391 padding: 20,
4392 },
4393 steps: {
4394 flexDirection: "row",
4395 justifyContent: "space-around",
4396 padding: 20,
4397 borderBottomWidth: 1,
4398 },
4399 stepIndicator: {
4400 alignItems: "center",
4401 },
4402 stepCircle: {
4403 width: 36,
4404 height: 36,
4405 borderRadius: 18,
4406 alignItems: "center",
4407 justifyContent: "center",
4408 marginBottom: 8,
4409 },
4410 stepNumber: {
4411 fontSize: 16,
4412 fontWeight: "600",
4413 },
4414 stepLabel: {
4415 fontSize: 12,
4416 },
4417 content: {
4418 flex: 1,
4419 },
4420 errorText: {
4421 fontSize: 16,
4422 textAlign: "center",
4423 },
4424 })
4425 ```
4426
4427 The `CheckoutScreen` component includes the following state variables:
4428
4429 - `currentStep`: The current step in the checkout process.
4430 - `loading`: A boolean indicating whether an operation is in progress.
4431 - Contact and address fields for shipping and billing.
4432 - Shipping options and the selected shipping option.
4433 - Payment providers and the selected payment provider.
4434
4435 Next, you'll handle updating the state variables when the cart changes. Replace the `// TODO update state when cart changes` comment with the following:
4436
4437 ```tsx title="app/checkout.tsx"
4438 useEffect(() => {
4439 // Populate form with existing cart data or reset to empty values
4440 setEmail(cart?.email || "")
4441 setShippingAddress({
4442 firstName: cart?.shipping_address?.first_name || "",
4443 lastName: cart?.shipping_address?.last_name || "",
4444 address: cart?.shipping_address?.address_1 || "",
4445 city: cart?.shipping_address?.city || "",
4446 postalCode: cart?.shipping_address?.postal_code || "",
4447 countryCode: cart?.shipping_address?.country_code || "",
4448 phone: cart?.shipping_address?.phone || "",
4449 })
4450
4451 // Billing address - check if different from shipping
4452 const hasDifferentBilling = cart?.billing_address &&
4453 (cart.billing_address.address_1 !== cart.shipping_address?.address_1 ||
4454 cart.billing_address.city !== cart.shipping_address?.city)
4455
4456 setUseSameForBilling(!hasDifferentBilling)
4457 setBillingAddress({
4458 firstName: cart?.billing_address?.first_name || "",
4459 lastName: cart?.billing_address?.last_name || "",
4460 address: cart?.billing_address?.address_1 || "",
4461 city: cart?.billing_address?.city || "",
4462 postalCode: cart?.billing_address?.postal_code || "",
4463 countryCode: cart?.billing_address?.country_code || "",
4464 phone: cart?.billing_address?.phone || "",
4465 })
4466
4467 // Reset selections when cart is null
4468 if (!cart) {
4469 setSelectedShippingOption(null)
4470 setSelectedPaymentProvider(null)
4471 setCurrentStep("delivery")
4472 }
4473 }, [cart])
4474
4475 // TODO fetch shipping options and payment providers
4476 ```
4477
4478 A `useEffect` hook populates the form fields with existing cart data when the cart changes.
4479
4480 Next, you'll fetch the available shipping options and payment providers when the user reaches the respective steps. Replace the `// TODO fetch shipping options and payment providers` comment with the following:
4481
4482 export const fetchCheckoutHighlights = [
4483 ["1", "fetchShippingOptions", "Retrieve shipping options for the cart"],
4484 ["18", "fetchPaymentProviders", "Retrieve payment providers for the cart's region"],
4485 ["35", "useEffect", "Call fetch functions when navigating to shipping or payment steps"]
4486 ]
4487
4488 ```tsx title="app/checkout.tsx" highlights={fetchCheckoutHighlights}
4489 const fetchShippingOptions = useCallback(async () => {
4490 if (!cart) {return}
4491
4492 try {
4493 setLoading(true)
4494 const { shipping_options } = await sdk.store.fulfillment.listCartOptions({
4495 cart_id: cart.id,
4496 })
4497 setShippingOptions(shipping_options || [])
4498 } catch (err) {
4499 console.error("Failed to fetch shipping options:", err)
4500 Alert.alert("Error", "Failed to load shipping options")
4501 } finally {
4502 setLoading(false)
4503 }
4504 }, [cart])
4505
4506 const fetchPaymentProviders = useCallback(async () => {
4507 if (!cart) {return}
4508
4509 try {
4510 setLoading(true)
4511 const { payment_providers } = await sdk.store.payment.listPaymentProviders({
4512 region_id: cart.region_id || "",
4513 })
4514 setPaymentProviders(payment_providers || [])
4515 } catch (err) {
4516 console.error("Failed to fetch payment providers:", err)
4517 Alert.alert("Error", "Failed to load payment providers")
4518 } finally {
4519 setLoading(false)
4520 }
4521 }, [cart])
4522
4523 useEffect(() => {
4524 if (currentStep === "shipping") {
4525 fetchShippingOptions()
4526 } else if (currentStep === "payment") {
4527 fetchPaymentProviders()
4528 }
4529 }, [currentStep, fetchShippingOptions, fetchPaymentProviders])
4530
4531 // TODO handle step transitions and order placement
4532 ```
4533
4534 You add a `fetchShippingOptions` function that retrieves shipping options, and a `fetchPaymentProviders` function that retrieves payment providers from the Medusa backend.
4535
4536 You also add a `useEffect` hook that calls these functions when the user navigates to the shipping or payment steps.
4537
4538 Next, you'll add functions that handle moving between steps and placing the order. Replace the `// TODO handle step transitions and order placement` comment with the following:
4539
4540 export const handleStepTransitions = [
4541 ["1", "handleDeliveryNext", "Validate and save delivery information, then go to shipping step"],
4542 ["60", "handleShippingNext", "Validate and save selected shipping option, then go to payment step"],
4543 ["83", "handlePlaceOrder", "Validate and place the order, then navigate to order confirmation"]
4544 ]
4545
4546 ```tsx title="app/checkout.tsx" highlights={handleStepTransitions}
4547 const handleDeliveryNext = async () => {
4548 // Validate shipping address
4549 if (!email || !shippingAddress.firstName || !shippingAddress.lastName ||
4550 !shippingAddress.address || !shippingAddress.city || !shippingAddress.postalCode ||
4551 !shippingAddress.countryCode || !shippingAddress.phone) {
4552 Alert.alert("Error", "Please fill in all shipping address fields")
4553 return
4554 }
4555
4556 // Validate billing address if different
4557 if (!useSameForBilling) {
4558 if (!billingAddress.firstName || !billingAddress.lastName || !billingAddress.address ||
4559 !billingAddress.city || !billingAddress.postalCode || !billingAddress.countryCode ||
4560 !billingAddress.phone) {
4561 Alert.alert("Error", "Please fill in all billing address fields")
4562 return
4563 }
4564 }
4565
4566 if (!cart) {return}
4567
4568 try {
4569 setLoading(true)
4570 const shippingAddressData = {
4571 first_name: shippingAddress.firstName,
4572 last_name: shippingAddress.lastName,
4573 address_1: shippingAddress.address,
4574 city: shippingAddress.city,
4575 postal_code: shippingAddress.postalCode,
4576 country_code: shippingAddress.countryCode,
4577 phone: shippingAddress.phone,
4578 }
4579
4580 const billingAddressData = useSameForBilling ? shippingAddressData : {
4581 first_name: billingAddress.firstName,
4582 last_name: billingAddress.lastName,
4583 address_1: billingAddress.address,
4584 city: billingAddress.city,
4585 postal_code: billingAddress.postalCode,
4586 country_code: billingAddress.countryCode,
4587 phone: billingAddress.phone,
4588 }
4589
4590 await sdk.store.cart.update(cart.id, {
4591 email,
4592 shipping_address: shippingAddressData,
4593 billing_address: billingAddressData,
4594 })
4595
4596 await refreshCart()
4597 setCurrentStep("shipping")
4598 } catch (err) {
4599 console.error("Failed to update cart:", err)
4600 Alert.alert("Error", "Failed to save delivery information")
4601 } finally {
4602 setLoading(false)
4603 }
4604 }
4605
4606 const handleShippingNext = async () => {
4607 if (!selectedShippingOption || !cart) {
4608 Alert.alert("Error", "Please select a shipping method")
4609 return
4610 }
4611
4612 try {
4613 setLoading(true)
4614
4615 await sdk.store.cart.addShippingMethod(cart.id, {
4616 option_id: selectedShippingOption,
4617 })
4618
4619 await refreshCart()
4620 setCurrentStep("payment")
4621 } catch (err) {
4622 console.error("Failed to add shipping method:", err)
4623 Alert.alert("Error", "Failed to save shipping method")
4624 } finally {
4625 setLoading(false)
4626 }
4627 }
4628
4629 const handlePlaceOrder = async () => {
4630 if (!selectedPaymentProvider || !cart) {
4631 Alert.alert("Error", "Please select a payment provider")
4632 return
4633 }
4634
4635 try {
4636 setLoading(true)
4637
4638 // Create payment session
4639 await sdk.store.payment.initiatePaymentSession(cart, {
4640 provider_id: selectedPaymentProvider,
4641 })
4642
4643 // Complete cart (converts cart to order on backend)
4644 const result = await sdk.store.cart.complete(cart.id)
4645
4646 if (result.type === "order") {
4647 // Navigate to order confirmation first
4648 // Cart will be cleared on the order confirmation page to prevent empty cart flash
4649 // TODO navigate to order confirmation screen with order details
4650 } else {
4651 Alert.alert("Error", result.error?.message || "Failed to complete order")
4652 }
4653 } catch (err: any) {
4654 console.error("Failed to complete order:", err)
4655 Alert.alert("Error", err?.message || "Failed to complete order")
4656 } finally {
4657 setLoading(false)
4658 }
4659 }
4660
4661 // TODO render step components
4662 ```
4663
4664 The following functions are added:
4665
4666 - `handleDeliveryNext`: Validates the delivery information, updates the cart with the email and addresses, and moves to the shipping step.
4667 - `handleShippingNext`: Validates the selected shipping option, adds it to the cart, and moves to the payment step.
4668 - `handlePlaceOrder`: Validates the selected payment provider, initiates the payment session, completes the cart, and handles the order confirmation. This function should also navigate to an order confirmation screen, which you'll implement later.
4669
4670 Finally, you'll render the appropriate step component based on the current step. Replace the `// TODO render step components` comment with the following:
4671
4672 ```tsx title="app/checkout.tsx"
4673 if (!cart) {
4674 return (
4675 <View style={[styles.centerContainer, { backgroundColor: colors.background }]}>
4676 <Text style={[styles.errorText, { color: colors.text }]}>
4677 No cart found. Please add items to your cart first.
4678 </Text>
4679 </View>
4680 )
4681 }
4682
4683 // Active step uses inverted colors: white bg with dark text in dark mode, tint bg with white text in light mode
4684 const activeStepBg = colorScheme === "dark" ? "#fff" : colors.tint
4685 const activeStepText = colorScheme === "dark" ? "#000" : "#fff"
4686
4687 return (
4688 <View style={[styles.container, { backgroundColor: colors.background }]}>
4689 <View style={[styles.steps, { borderBottomColor: colors.border }]}>
4690 {(["delivery", "shipping", "payment"] as CheckoutStep[]).map((step, index) => (
4691 <View key={step} style={styles.stepIndicator}>
4692 <View
4693 style={[
4694 styles.stepCircle,
4695 {
4696 backgroundColor:
4697 currentStep === step ? activeStepBg : colors.icon + "30",
4698 },
4699 ]}
4700 >
4701 <Text
4702 style={[
4703 styles.stepNumber,
4704 { color: currentStep === step ? activeStepText : colors.icon },
4705 ]}
4706 >
4707 {index + 1}
4708 </Text>
4709 </View>
4710 <Text
4711 style={[
4712 styles.stepLabel,
4713 {
4714 color: currentStep === step ? colors.text : colors.icon,
4715 fontWeight: currentStep === step ? "600" : "400",
4716 },
4717 ]}
4718 >
4719 {step.charAt(0).toUpperCase() + step.slice(1)}
4720 </Text>
4721 </View>
4722 ))}
4723 </View>
4724
4725 <View style={styles.content}>
4726 {currentStep === "delivery" && (
4727 <DeliveryStep
4728 email={email}
4729 shippingAddress={shippingAddress}
4730 billingAddress={billingAddress}
4731 useSameForBilling={useSameForBilling}
4732 loading={loading}
4733 onEmailChange={setEmail}
4734 onShippingAddressChange={(field, value) =>
4735 setShippingAddress((prev) => ({ ...prev, [field]: value }))
4736 }
4737 onBillingAddressChange={(field, value) =>
4738 setBillingAddress((prev) => ({ ...prev, [field]: value }))
4739 }
4740 onUseSameForBillingChange={setUseSameForBilling}
4741 onNext={handleDeliveryNext}
4742 />
4743 )}
4744
4745 {currentStep === "shipping" && (
4746 <ShippingStep
4747 shippingOptions={shippingOptions}
4748 selectedShippingOption={selectedShippingOption}
4749 currencyCode={cart.currency_code}
4750 loading={loading}
4751 onSelectOption={setSelectedShippingOption}
4752 onBack={() => setCurrentStep("delivery")}
4753 onNext={handleShippingNext}
4754 />
4755 )}
4756
4757 {currentStep === "payment" && (
4758 <PaymentStep
4759 cart={cart}
4760 paymentProviders={paymentProviders}
4761 selectedPaymentProvider={selectedPaymentProvider}
4762 loading={loading}
4763 onSelectProvider={setSelectedPaymentProvider}
4764 onBack={() => setCurrentStep("shipping")}
4765 onPlaceOrder={handlePlaceOrder}
4766 />
4767 )}
4768 </View>
4769 </View>
4770 )
4771 ```
4772
4773 If the cart isn't set, a message prompts the user to add items to their cart.
4774
4775 Otherwise, the step indicators are rendered at the top of the screen, and the current step's component is shown.
4776
4777 ### Add Checkout Screen to Navigation
4778
4779 Next, you'll add the checkout screen to the app's navigation structure. You'll add it as a top-level stack screen.
4780
4781 In `app/_layout.tsx`, Replace the `TODO: Add checkout and order confirmation screens` comment with the following:
4782
4783 ```tsx title="app/_layout.tsx"
4784 <Stack.Screen
4785 name="checkout"
4786 options={{
4787 headerShown: true,
4788 title: "Checkout",
4789 presentation: "card",
4790 headerBackButtonDisplayMode: "minimal",
4791 }}
4792 />
4793 ```
4794
4795 ### Update Cart Screen to Navigate to Checkout
4796
4797 Finally, you'll update the cart screen to navigate to the checkout screen when the user taps the "Proceed to Checkout" button.
4798
4799 In `app/(drawer)/(tabs)/(cart)/index.tsx`, find the `Button` at the end of the `CartScreen` component's `return` statement, and change the `onPress` prop to the following:
4800
4801 ```tsx title="app/(drawer)/(tabs)/(cart)/index.tsx"
4802 <Button
4803 title="Proceed to Checkout"
4804 onPress={() => router.push("/checkout")}
4805 loading={loading}
4806 />
4807 ```
4808
4809 If you get a type error regarding the `/checkout` route, the error will be resolved when you run the app.
4810
4811 ### Test the Checkout Flow
4812
4813 To test the checkout flow, run your Medusa application and Expo app.
4814
4815 Then, in your Expo app, click on the "Proceed to Checkout" button in the cart screen. You should be taken to the checkout screen with the Delivery step as the current step.
4816
4817 In the Delivery step, fill in the email and address fields, then click "Continue" to proceed to the Shipping step.
4818
4819 ![Delivery step with address filled](https://res.cloudinary.com/dza7lstvk/image/upload/v1762360359/Medusa%20Resources/CleanShot_2025-11-05_at_18.31.49_2x_jl3q4g.png)
4820
4821 Then, in the Shipping step, select a shipping method and click "Continue" to proceed to the Payment step.
4822
4823 ![Shipping step with shipping method selected](https://res.cloudinary.com/dza7lstvk/image/upload/v1762360359/Medusa%20Resources/CleanShot_2025-11-05_at_18.31.49_2x_jl3q4g.png)
4824
4825 Finally, in the Payment step, select a payment provider. You currently can place an order, but there is no order confirmation screen yet. You'll add it in the next step.
4826
4827 ![Payment step with payment provider selected](https://res.cloudinary.com/dza7lstvk/image/upload/v1762360464/Medusa%20Resources/CleanShot_2025-11-05_at_18.33.59_2x_eled5o.png)
4828
4829 ---
4830
4831 ## Step 12: Create Order Confirmation Screen
4832
4833 The last step in this tutorial is to create an order confirmation screen that customers are taken to after successfully placing an order.
4834
4835 You'll implement the order confirmation screen, then add it to the navigation structure.
4836
4837 ### Create Order Confirmation Screen Component
4838
4839 To create the order confirmation screen, create the file `app/order-confirmation/[id].tsx` with the following content:
4840
4841 ```tsx title="app/order-confirmation/[id].tsx" collapsibleLines="31-181" expandButtonLabel="Show Styles"
4842 import { Loading } from "@/components/loading"
4843 import { Button } from "@/components/ui/button"
4844 import { IconSymbol } from "@/components/ui/icon-symbol"
4845 import { Colors } from "@/constants/theme"
4846 import { useCart } from "@/context/cart-context"
4847 import { useColorScheme } from "@/hooks/use-color-scheme"
4848 import { formatPrice } from "@/lib/format-price"
4849 import { getPaymentProviderInfo } from "@/lib/payment-providers"
4850 import { sdk } from "@/lib/sdk"
4851 import type { HttpTypes } from "@medusajs/types"
4852 import { Image } from "expo-image"
4853 import { useLocalSearchParams, useRouter } from "expo-router"
4854 import React, { useCallback, useEffect, useRef, useState } from "react"
4855 import { ScrollView, StyleSheet, Text, View } from "react-native"
4856
4857 export default function OrderConfirmationScreen() {
4858 const { id } = useLocalSearchParams<{ id: string }>()
4859 const router = useRouter()
4860 const colorScheme = useColorScheme()
4861 const colors = Colors[colorScheme ?? "light"]
4862 const { clearCart } = useCart()
4863
4864 const [order, setOrder] = useState<HttpTypes.StoreOrder | null>(null)
4865 const [loading, setLoading] = useState(true)
4866 const [error, setError] = useState<string | null>(null)
4867 const hasCleared = useRef(false)
4868
4869 // TODO fetch order details and clear cart
4870 }
4871
4872 const styles = StyleSheet.create({
4873 container: {
4874 flex: 1,
4875 },
4876 centerContainer: {
4877 flex: 1,
4878 justifyContent: "center",
4879 alignItems: "center",
4880 padding: 20,
4881 },
4882 content: {
4883 padding: 20,
4884 },
4885 successIcon: {
4886 width: 80,
4887 height: 80,
4888 borderRadius: 40,
4889 alignItems: "center",
4890 justifyContent: "center",
4891 alignSelf: "center",
4892 marginBottom: 24,
4893 },
4894 checkmark: {
4895 fontSize: 48,
4896 color: "#fff",
4897 fontWeight: "700",
4898 },
4899 title: {
4900 fontSize: 28,
4901 fontWeight: "700",
4902 textAlign: "center",
4903 marginBottom: 8,
4904 },
4905 subtitle: {
4906 fontSize: 16,
4907 textAlign: "center",
4908 marginBottom: 32,
4909 },
4910 card: {
4911 borderWidth: 1,
4912 borderRadius: 12,
4913 padding: 16,
4914 marginBottom: 16,
4915 },
4916 cardTitle: {
4917 fontSize: 18,
4918 fontWeight: "700",
4919 marginBottom: 16,
4920 },
4921 infoRow: {
4922 flexDirection: "row",
4923 justifyContent: "space-between",
4924 marginBottom: 12,
4925 },
4926 label: {
4927 fontSize: 14,
4928 },
4929 value: {
4930 fontSize: 14,
4931 fontWeight: "500",
4932 },
4933 sectionTitle: {
4934 fontSize: 16,
4935 fontWeight: "600",
4936 marginTop: 16,
4937 marginBottom: 8,
4938 },
4939 addressText: {
4940 fontSize: 14,
4941 marginBottom: 4,
4942 },
4943 paymentMethodRow: {
4944 flexDirection: "row",
4945 alignItems: "center",
4946 marginBottom: 4,
4947 },
4948 itemRow: {
4949 flexDirection: "row",
4950 alignItems: "center",
4951 marginBottom: 16,
4952 paddingBottom: 16,
4953 borderBottomWidth: 1,
4954 },
4955 lastItemRow: {
4956 borderBottomWidth: 0,
4957 marginBottom: 0,
4958 paddingBottom: 0,
4959 },
4960 itemImage: {
4961 width: 60,
4962 height: 60,
4963 borderRadius: 8,
4964 marginRight: 12,
4965 },
4966 itemInfo: {
4967 flex: 1,
4968 },
4969 itemTitle: {
4970 fontSize: 14,
4971 fontWeight: "600",
4972 marginBottom: 4,
4973 },
4974 itemVariant: {
4975 fontSize: 12,
4976 marginBottom: 4,
4977 },
4978 itemQuantity: {
4979 fontSize: 12,
4980 },
4981 itemPrice: {
4982 fontSize: 14,
4983 fontWeight: "600",
4984 marginLeft: 12,
4985 },
4986 summaryRow: {
4987 flexDirection: "row",
4988 justifyContent: "space-between",
4989 marginBottom: 12,
4990 },
4991 summaryLabel: {
4992 fontSize: 14,
4993 },
4994 summaryValue: {
4995 fontSize: 14,
4996 fontWeight: "500",
4997 },
4998 totalRow: {
4999 marginTop: 12,
5000 paddingTop: 12,
Showing first 5,000 of 5,389 lines. View raw