# react-native-router-dom
**Repository Path**: ws18250840411/react-native-router-dom
## Basic Information
- **Project Name**: react-native-router-dom
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2026-01-09
- **Last Updated**: 2026-03-17
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# react-native-router-dom
[](https://www.npmjs.com/package/react-native-router-dom)
[](https://github.com/nicepkg/react-native-router-dom/blob/main/LICENSE)
[](https://bundlephobia.com/package/react-native-router-dom)
[](https://www.typescriptlang.org/)
[](https://reactnavigation.org/)
> [中文文档](./README.md)
**If you know react-router-dom, you already know this library.**
A **react-router-dom-like routing API** for React Native: `useNavigate`, `useLocation`, `useParams`, ``, ``... nearly identical usage with zero learning curve. Under the hood it maps to React Navigation (Stack/Tabs) automatically — you just define your routes.
## Why react-native-router-dom?
- **Zero learning curve** — API mirrors react-router-dom; if you can write Web routes, you can write RN routes
- **Dead simple** — One `RouteProps[]` config + one ``, three lines to get routing
- **Unified mental model** — Same routing patterns for Web and RN, no context switching
- **Batteries included** — React Navigation v7 bundled, no manual Navigator tree setup
### Side-by-side: react-router-dom vs react-native-router-dom
**react-router-dom (Web):**
```tsx
// Define routes
} />
} />
}>
} />
} />
// Inside a screen
const navigate = useNavigate();
navigate('/user/42');
navigate(-1);
const { id } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
```
**react-native-router-dom (RN) — almost identical:**
```tsx
// Define routes (config-driven, even simpler)
const routes: RouteProps[] = [
{ path: '/home', element: Home },
{ path: '/user/:id', element: User },
{ path: '/settings', element: SettingsLayout, children: [
{ index: true, element: SettingsHome },
{ path: 'detail', element: SettingsDetail },
]},
];
// Inside a screen — exactly the same!
const navigate = useNavigate();
navigate('/user/42');
navigate(-1);
const { id } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
```
> Hooks and components work **identically**. The only difference is route definitions use config objects instead of JSX — a better fit for React Native's declarative patterns.
## Highlights
| Feature | Description |
|---------|-------------|
| **Config-driven** | Single `RouteProps[]` drives Stack/Tabs |
| **Unified navigation** | `navigate('/settings/detail')` works across Tabs and nested stacks |
| **Nested routes** | `` + index routes, same as react-router |
| **Guards** | Global `beforeEach` + per-route `guard`, async support |
| **Error boundary** | `errorFallback` / `RouterErrorBoundary` — per-screen crash isolation |
| **Web linking** | History / hash mode, direct URLs, refresh, back/forward |
| **TypeScript** | Full type exports, strict inference |
| **Zero config** | React Navigation v7 bundled as dependency |
| **Tiny** | ESM gzip **~7.3 KB** — see bundle details below |
## Bundle size
| Output | Raw | gzip |
|--------|-----|------|
| `dist/index.mjs` (ESM) | 22.0 KB | **~7.3 KB** |
| `dist/index.js` (CJS) | 23.5 KB | **~8.0 KB** |
| `dist/index.d.ts` (types) | 8.5 KB | — |
> Minified (ESM via Terser, CJS via esbuild). Only one format is included in your app bundle.
## Compatibility
| Platform | Requirement |
|----------|-------------|
| React | >= 18.2.0 |
| React Native | >= 0.72 |
| React Navigation | v7 (bundled) |
| react-native-web | Supported |
| Hermes | Supported (built-in URLSearchParams fallback) |
| Expo | Supported (bare workflow or dev-client) |
## Installation
```bash
npm i react-native-router-dom
```
### Peer dependencies
```bash
npm i react-native-screens react-native-safe-area-context
```
> After installing, run `cd ios && pod install` for iOS.
## Quick start
### 1) Define routes
```ts
import type { RouteProps } from 'react-native-router-dom';
import { Login } from './Login';
import { Home } from './Home';
export const routes: RouteProps[] = [
{ path: '/login', element: Login, options: { headerShown: false } },
{ path: '/home', element: Home, options: { title: 'Home' } },
];
```
### 2) Render RouterProvider
```tsx
import React from 'react';
import { RouterProvider, createNativeRouter } from 'react-native-router-dom';
import { routes } from './routes';
export default function App() {
const router = React.useMemo(() => createNativeRouter(routes), []);
return ;
}
```
## API at a glance
### RouteProps
| Field | Description |
|-------|-------------|
| `path` | Absolute (`/foo`), relative (`detail`), dynamic (`/user/:id`), or splat (`/docs/*`) |
| `index` | Index route (matches parent path) |
| `element` | Screen component or React element |
| `children` | Nested routes |
| `type` | `'stack'` (default) or `'tabs'` |
| `guard` | Per-route guard |
| `meta` | Arbitrary metadata |
| `options` | React Navigation screen options (transparent pass-through) |
| `navigatorOptions` | React Navigation navigator options (transparent pass-through) |
### RouterProvider
```ts
type RouterProviderProps = {
router?: NativeRouter;
routes?: RouteProps[];
beforeEach?: RouteGuard;
theme?: Theme;
fallback?: React.ReactNode;
errorFallback?: React.ReactNode | ((error: Error, reset: () => void) => React.ReactNode);
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
linking?: any;
prefixes?: string[];
linkingType?: 'history' | 'hash';
};
```
### Hooks
| Hook | Returns | Description |
|------|---------|-------------|
| `useNavigate()` | `(to, options?) => Promise` | Navigate programmatically |
| `useRouter()` | `{ push, replace, back, navigate }` | Shorthand navigation methods |
| `useNativeRouter()` | `NativeRouter` | Full router instance |
| `useLocation()` | `RouteLocation \| null` | Current pathname, search, hash, params, matches |
| `useParams()` | `Record` | Dynamic and splat params |
| `useSearchParams([defaults])` | `[SearchParamsLike, setter]` | Read/update query string |
| `useMatch(pattern)` | `{ pathname, params, pattern } \| null` | Match current pathname |
| `useOutletContext()` | `T` | Data from parent Outlet |
| `useBlocker(blocker)` | `void` | Block navigation (unsaved form, etc.) |
| `useInRouterContext()` | `boolean` | `true` inside `` |
### Guards
- **Global**: `createNativeRouter(routes, { beforeEach })` or `router.beforeEach(fn)`.
- **Per-route**: `route.guard`.
- **Return values**: `true`/`undefined` → allow, `false` → block, `string` or `redirect(to, { replace? })` → redirect.
- **Async**: Guards support `async` / `Promise`.
```ts
import { redirect } from 'react-native-router-dom';
router.beforeEach(({ to }) => {
const requiresAuth = to.matches.some(m => (m.route.meta as any)?.requiresAuth);
if (!requiresAuth) return true;
return redirect('/login');
});
```
### Components
| Component | Description |
|-----------|-------------|
| `` | Pressable navigation link |
| `` | Link with `isActive` state (supports `style` / `children` as functions) |
| `` | Declarative redirect |
| `` | Nested route outlet |
| `` | Error isolation boundary |
### Utilities
| Utility | Description |
|---------|-------------|
| `generatePath(pattern, params)` | Fill `:id` and `*` in path pattern |
| `redirect(to, { replace? })` | Create redirect object for guards |
| `isRedirect(value)` | Type guard for Redirect |
| `createLinking(routes, { prefixes })` | Generate React Navigation linking config |
## Web linking (react-native-web)
- **History mode** (default): Direct URLs, refresh, back/forward. Requires `historyApiFallback: true`.
- **Hash mode**: `linkingType="hash"` — URLs like `http://localhost/#/settings`.
## react-router-dom comparison
| react-router-dom | react-native-router-dom | Notes |
|-------------------|--------------------------|-------|
| `BrowserRouter` | `RouterProvider` | Config-driven entry |
| `` / `` | `RouteProps[]` | No JSX routes |
| `` / `` | `` / `` | Same API |
| `` | `` | Declarative redirect |
| `` | `` | Nested outlet |
| `useNavigate` | `useNavigate` | Programmatic nav |
| `useLocation` | `useLocation` | Current location |
| `useParams` | `useParams` | Dynamic params |
| `useSearchParams` | `useSearchParams` | With Hermes fallback |
| `useMatch` | `useMatch` | Pattern matching |
| `useBlocker` | `useBlocker` | Navigation blocking |
| `generatePath` | `generatePath` | Path generation |
| — | `beforeEach` / `guard` | Route guards (no RR equivalent) |
| — | `RouterErrorBoundary` | Per-route error isolation |
| — | `createLinking` | Deep linking config |
## Demo
```bash
cd demo && npm i
npm run ios # or android / web
npm test # 45 test cases
```
## Contributing
Issues and PRs are welcome.
```bash
git clone https://gitee.com/ws18250840411/react-native-router-dom.git
cd react-native-router-dom
npm i
npm run typecheck # type check
npm run build # build
cd demo
npm i && npm test # run tests
```
## License
[MIT](./LICENSE)