0Pricing
React Native Academy · บทเรียน

การกำหนดค่า Deep Link ของ React Navigation

กำหนดค่าพร็อพ linking บน NavigationContainer พร้อมแผนผังหน้าจอ เพื่อให้ React Navigation นำทางไปยังหน้าจอที่ถูกต้องโดยอัตโนมัติเมื่อเปิด deep link

การกำหนดค่า Deep Link ของ React Navigation เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

React Navigation Built-In Deep Linking

React Navigation provides built-in deep linking support via a linking prop on the NavigationContainer. When configured, React Navigation automatically handles both cold-start and warm-start URLs by parsing them against a screen map and navigating to the matching screen — you don't need to write URL parsing or Linking API code manually.

This declarative approach is far less error-prone than manual URL handling and integrates seamlessly with the navigation library's state management.

import { NavigationContainer } from '@react-navigation/native';

const linking = {
  prefixes: ['myapp://'],
  config: {
    screens: {
      Home: 'home',
      Profile: 'profile/:userId',
      Settings: 'settings',
    },
  },
};

<NavigationContainer linking={linking}>
  <RootNavigator />
</NavigationContainer>

The linking Prop: prefixes and config

The linking prop has two main fields: prefixes (an array of URL prefixes to handle) and config (the screen map). The prefixes array tells React Navigation which URL schemes to intercept. You can include both your custom scheme and your HTTPS domain for universal links.

The config.screens object maps screen component names to URL path patterns. The URL path after the prefix is matched against these patterns to determine which screen to navigate to.

const linking = {
  prefixes: [
    'myapp://',
    'https://www.myapp.com',  // universal links too
    'https://myapp.com',
  ],
  config: {
    screens: {
      Home: '',           // matches myapp:// (empty path)
      Profile: 'profile/:userId',   // myapp://profile/123
      Product: 'product/:id',        // myapp://product/abc
      Settings: 'settings',          // myapp://settings
    },
  },
};

Path Parameters and Query Strings

URL path parameters are defined with a colon prefix like :userId. When a URL matches, the parameter is automatically extracted and passed as a route param to the screen component. Query string parameters are also automatically parsed and added to route params.

For example, myapp://profile/123?tab=posts matches profile/:userId and the screen receives route.params = { userId: '123', tab: 'posts' }. No manual URL parsing needed.

// URL: myapp://profile/123?tab=posts
// Matches: profile/:userId
// Screen receives:
// route.params = { userId: '123', tab: 'posts' }

function ProfileScreen({ route }) {
  const { userId, tab } = route.params;
  // userId = '123', tab = 'posts'
}

Nested Navigator Configuration

When screens are inside nested navigators (e.g., a tab navigator with stacks in each tab), the screen map must reflect the nesting structure. Use a screens key inside the parent screen's config to define nested screen paths.

React Navigation handles the navigation state correctly — it sets up the entire stack needed to arrive at the deeply nested screen, including any parent navigators that need to be initialized first.

const linking = {
  prefixes: ['myapp://'],
  config: {
    screens: {
      Tabs: {                    // bottom tab navigator
        screens: {
          HomeTab: {             // home tab stack
            screens: {
              Home: 'home',
              PostDetail: 'post/:postId',
            },
          },
          ProfileTab: {          // profile tab stack
            screens: {
              Profile: 'profile/:userId',
            },
          },
        },
      },
    },
  },
};

Exact Path Matching

By default React Navigation does prefix matching on paths. Add exact: true to a screen config to require an exact path match instead. Exact matching is important when paths could partially match multiple screens.

For example, without exact matching, the pattern post would match myapp://post and also myapp://post-list. With exact: true only the precise path matches.

const linking = {
  prefixes: ['myapp://'],
  config: {
    screens: {
      PostList: {
        path: 'post',
        exact: true,  // only matches exactly myapp://post
      },
      PostDetail: 'post/:id', // matches myapp://post/123
    },
  },
};

Custom Parse and Stringify Functions

The linking config also accepts parse and stringify functions per screen to transform route params before passing them to the component. parse converts URL param strings to the correct types (e.g., string '123' to number 123). stringify converts params back to URL strings for link generation.

These functions give you full control over param transformation without needing to implement URL parsing yourself.

const linking = {
  prefixes: ['myapp://'],
  config: {
    screens: {
      Profile: {
        path: 'profile/:userId',
        parse: {
          userId: (id) => Number(id),  // string to number
        },
        stringify: {
          userId: (id) => String(id),  // number back to string
        },
      },
    },
  },
};

getPathFromState and getStateFromPath

React Navigation provides getPathFromState and getStateFromPath utilities that convert between navigation state objects and URL path strings. These are useful for generating shareable deep links from the current navigation state and for custom state restoration logic.

getPathFromState(state, config) returns a URL path for the current navigation state. getStateFromPath(path, config) returns a navigation state for a given URL. Both require the same config object used in the linking prop.

import { getPathFromState, getStateFromPath } from '@react-navigation/native';

// Generate a shareable link for the current screen:
const currentState = navigationRef.current.getRootState();
const path = getPathFromState(currentState, linking.config);
const shareUrl = 'myapp://' + path;
// shareUrl = 'myapp://profile/123'

// Parse a URL to a navigation state:
const state = getStateFromPath('profile/123', linking.config);
// state = { routes: [{ name: 'Profile', params: { userId: '123' } }] }

Enabling Deep Links in Expo (Expo Go)

When running in Expo Go during development, your app's deep link URL uses the exp:// scheme with the Expo Go host. React Navigation handles this automatically when you include Linking.createURL('') in the prefixes array (using the expo-linking package), which resolves to the correct prefix for both Expo Go and production builds.

This means your deep link config works in both development (Expo Go) and production (your app's custom scheme) without any changes to the config.

import * as ExpoLinking from 'expo-linking';

const linking = {
  prefixes: [
    ExpoLinking.createURL('/'), // works in Expo Go AND production
    'myapp://',
    'https://www.myapp.com',
  ],
  config: {
    screens: {
      Home: '',
      Profile: 'profile/:userId',
    },
  },
};

Generating Deep Links Programmatically

Use Linking.createURL(path, options) from expo-linking to generate deep link URLs that work in both development and production. Pass query params in the queryParams option. Use the generated URLs in notifications, share sheets, and email campaigns.

This approach is safer than hardcoding scheme URLs because createURL produces the correct prefix for the current runtime environment automatically.

import * as ExpoLinking from 'expo-linking';

// Generate a profile deep link:
const profileLink = ExpoLinking.createURL('profile/123', {
  queryParams: { tab: 'posts', source: 'share_button' },
});
// In production: 'myapp://profile/123?tab=posts&source=share_button'
// In Expo Go: 'exp://127.0.0.1:19000/--/profile/123?tab=posts...'

await Share.share({ url: profileLink });

Testing the Linking Configuration

React Navigation provides a linking debug tool — set linking.enabled: 'auto' and the library logs URL matching results to the console in development. This helps diagnose why a URL is not navigating to the expected screen.

For comprehensive testing, write a test function that calls getStateFromPath with each of your expected deep link URLs and asserts the resulting navigation state is correct. This catches config errors before they reach users.

// Test your linking config:
import { getStateFromPath } from '@react-navigation/native';

const testCases = [
  { url: 'profile/123', expected: 'Profile' },
  { url: 'product/abc', expected: 'Product' },
  { url: 'settings', expected: 'Settings' },
];

testCases.forEach(({ url, expected }) => {
  const state = getStateFromPath(url, linking.config);
  const routeName = state.routes[0].name;
  console.assert(routeName === expected, 'Mismatch for ' + url);
});

Not Found Screen for Invalid Links

Configure a fallback screen for URLs that don't match any defined pattern. In the linking config, add a NotFound screen and set it as the fallback. This is important because deep links from third parties may use incorrect paths, and you should gracefully show a useful message instead of crashing or silently failing.

The not-found screen should explain that the link is no longer valid, provide a way to navigate to the home screen, and optionally log the invalid URL for analysis.

const linking = {
  prefixes: ['myapp://'],
  config: {
    screens: {
      Home: '',
      Profile: 'profile/:userId',
      NotFound: '*',  // catch-all for unmatched paths
    },
  },
};

function NotFoundScreen() {
  const navigation = useNavigation();
  return (
    <View>
      <Text>This link is no longer valid.</Text>
      <Button
        title='Go Home'
        onPress={() => navigation.replace('Home')}
      />
    </View>
  );
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: the linking prop on NavigationContainer automatically handles deep link parsing and navigation using a declarative screen map, nested navigators are supported by nesting screens configs within parent screen configs, and ExpoLinking.createURL generates environment-aware deep links that work in both Expo Go and production builds. Next up we configure universal links using HTTPS URLs with Apple App Site Association and Android App Links.

คำถามที่พบบ่อย

บทเรียน “การกำหนดค่า Deep Link ของ React Navigation” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การกำหนดค่า Deep Link ของ React Navigation” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดค่า Deep Link ของ React Navigation”

กำหนดค่าพร็อพ linking บน NavigationContainer พร้อมแผนผังหน้าจอ เพื่อให้ React Navigation นำทางไปยังหน้าจอที่ถูกต้องโดยอัตโนมัติเมื่อเปิด deep link คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การกำหนดค่า Deep Link ของ React Navigation” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การกำหนดโครงร่าง URL แบบกำหนดเอง
  2. API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL
  3. การกำหนดค่า Deep Link ของ React Navigation
  4. Universal Links (Deep Link ผ่าน HTTPS) บน iOS และ Android
← กลับไปที่ React Native Academy