Declarative routing for React Native applications with native-specific components and deep linking support
—
Complete re-export of React Router utility functions for path manipulation, route creation, data handling, and response generation in React Native applications.
Creates a memory-based router suitable for React Native applications and testing environments.
/**
* Creates a memory-based router for React Native
* @param routes - Array of route objects
* @param opts - Router configuration options
* @returns Router instance for use with RouterProvider
*/
function createMemoryRouter(
routes: RouteObject[],
opts?: {
basename?: string;
future?: Partial<RouterFutureConfig>;
hydrationData?: HydrationState;
initialEntries?: InitialEntry[];
initialIndex?: number;
dataStrategy?: DataStrategyFunction;
patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
}
): Router;Creates a path string from a partial path object.
/**
* Creates a path string from path object
* @param partialPath - Partial path object
* @returns Complete path string
*/
function createPath(partialPath: Partial<Path>): string;
interface Path {
pathname?: string;
search?: string;
hash?: string;
}Generates a path string from a pattern and parameters.
/**
* Generates path from pattern and parameters
* @param pattern - Path pattern with parameter placeholders
* @param params - Parameters to substitute in pattern
* @returns Generated path string
*/
function generatePath(pattern: string, params?: Params): string;
type Params = Record<string, string | number>;Parses a path string into its component parts.
/**
* Parses path string into components
* @param path - Path string to parse
* @returns Path object with pathname, search, and hash
*/
function parsePath(path: string): Path;Resolves a relative path against a base pathname.
/**
* Resolves relative path against base pathname
* @param path - Path to resolve (can be relative)
* @param fromPathname - Base pathname to resolve against
* @returns Resolved path object
*/
function resolvePath(path: To, fromPathname?: string): Path;
type To = string | Partial<Path>;Attempts to match a path pattern against a pathname.
/**
* Matches path pattern against pathname
* @param pattern - Pattern to match (string or PathPattern object)
* @param pathname - Pathname to test against pattern
* @returns PathMatch if successful, null otherwise
*/
function matchPath(
pattern: PathPattern | string,
pathname: string
): PathMatch | null;
interface PathPattern {
path: string;
caseSensitive?: boolean;
end?: boolean;
}
interface PathMatch {
params: Params;
pathname: string;
pathnameBase: string;
pattern: PathPattern;
}Matches a set of routes against a location.
/**
* Matches routes against location
* @param routes - Array of route objects to match
* @param locationArg - Location to match against
* @param basename - Optional basename for matching
* @returns Array of route matches or null
*/
function matchRoutes(
routes: RouteObject[],
locationArg: Partial<Location> | string,
basename?: string
): RouteMatch[] | null;
interface RouteMatch {
params: Params;
pathname: string;
pathnameBase: string;
route: RouteObject;
}Creates route objects from React children (JSX <Route> elements).
/**
* Creates route objects from React children
* @param children - JSX Route elements
* @param parentPath - Optional parent path for nested routes
* @returns Array of RouteObject instances
*/
function createRoutesFromChildren(
children: React.ReactNode,
parentPath?: number[]
): RouteObject[];Alias for createRoutesFromChildren. Creates route objects from React elements.
/**
* Alias for createRoutesFromChildren
* Creates route objects from React elements
* @param children - JSX Route elements
* @param parentPath - Optional parent path for nested routes
* @returns Array of RouteObject instances
*/
function createRoutesFromElements(
children: React.ReactNode,
parentPath?: number[]
): RouteObject[];Creates a JSON response for route loaders and actions.
/**
* Creates JSON response for loaders/actions
* @param object - Object to serialize as JSON
* @param init - Response initialization options
* @returns Response object with JSON content
*/
function json(object: any, init?: ResponseInit): Response;Creates a redirect response for route loaders and actions.
/**
* Creates redirect response
* @param url - URL to redirect to
* @param init - Response initialization options
* @returns Response object with redirect status
*/
function redirect(url: string, init?: ResponseInit): Response;Creates a document-level redirect response.
/**
* Creates document-level redirect response
* @param url - URL to redirect to
* @param init - Response initialization options
* @returns Response object with document redirect
*/
function redirectDocument(url: string, init?: ResponseInit): Response;Creates a replace response for navigation.
/**
* Creates replace response for navigation
* @param url - URL to replace current location
* @param init - Response initialization options
* @returns Response object with replace navigation
*/
function replace(url: string, init?: ResponseInit): Response;Creates a deferred response for streaming data in loaders.
/**
* Creates deferred response for streaming
* @param data - Object with promises for deferred loading
* @param init - Response initialization options
* @returns Response object with deferred data
*/
function defer(data: Record<string, unknown>, init?: ResponseInit): Response;Checks if an error is a route error response.
/**
* Type guard for route error responses
* @param error - Error to check
* @returns Boolean indicating if error is RouteErrorResponse
*/
function isRouteErrorResponse(error: any): error is ErrorResponse;
interface ErrorResponse {
status: number;
statusText: string;
data: any;
}Renders route matches into React elements.
/**
* Renders route matches into React elements
* @param matches - Route matches to render
* @returns React element tree for matches
*/
function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;import { createMemoryRouter, RouterProvider } from "react-router-native";
// Basic router setup
const router = createMemoryRouter([
{
path: "/",
element: <Home />,
},
{
path: "/products/:id",
element: <Product />,
loader: async ({ params }) => {
return fetch(`/api/products/${params.id}`);
},
},
]);
function App() {
return <RouterProvider router={router} />;
}
// Router with initial entries for deep linking
const deepLinkRouter = createMemoryRouter(
[
{ path: "/", element: <Home /> },
{ path: "/products/:id", element: <Product /> },
],
{
initialEntries: ["/", "/products/123"],
initialIndex: 1, // Start at /products/123
}
);import {
createPath,
generatePath,
parsePath,
resolvePath
} from "react-router-native";
// Create path from object
const path = createPath({
pathname: "/products",
search: "?sort=name",
hash: "#top"
});
// Result: "/products?sort=name#top"
// Generate path with parameters
const productPath = generatePath("/products/:id/reviews/:reviewId", {
id: "123",
reviewId: "456"
});
// Result: "/products/123/reviews/456"
// Parse path string
const parsed = parsePath("/products?sort=name#top");
// Result: { pathname: "/products", search: "?sort=name", hash: "#top" }
// Resolve relative path
const resolved = resolvePath("../settings", "/app/profile");
// Result: { pathname: "/app/settings", search: "", hash: "" }import { matchPath, matchRoutes } from "react-router-native";
// Match single path
const match = matchPath(
{ path: "/products/:id", caseSensitive: false },
"/products/123"
);
if (match) {
console.log(match.params.id); // "123"
}
// Match multiple routes
const routes = [
{ path: "/", element: <Home /> },
{ path: "/products/:id", element: <Product /> },
];
const matches = matchRoutes(routes, "/products/123");
if (matches) {
console.log(matches[0].params.id); // "123"
}import { json, redirect, defer } from "react-router-native";
// JSON response
export async function productLoader({ params }) {
const product = await fetchProduct(params.id);
return json(product, { status: 200 });
}
// Redirect response
export async function productAction({ request }) {
const formData = await request.formData();
const product = await updateProduct(formData);
return redirect(`/products/${product.id}`);
}
// Deferred response for streaming
export async function dashboardLoader() {
return defer({
user: getUserData(), // Fast query
analytics: getAnalytics(), // Slow query - will stream later
});
}import { createRoutesFromElements } from "react-router-native";
import { Route } from "react-router-native";
// Create routes from JSX
const routes = createRoutesFromElements(
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="products" element={<Products />}>
<Route index element={<ProductList />} />
<Route path=":id" element={<ProductDetail />} />
</Route>
</Route>
);
// Use with createMemoryRouter
const router = createMemoryRouter(routes);import { isRouteErrorResponse } from "react-router-native";
function ErrorBoundary() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return (
<View>
<Text>Error {error.status}: {error.statusText}</Text>
<Text>{error.data}</Text>
</View>
);
}
return (
<View>
<Text>Unknown error occurred</Text>
</View>
);
}// Router types
interface Router {
// Router implementation details
}
interface RouteObject {
path?: string;
index?: boolean;
children?: React.ReactNode;
caseSensitive?: boolean;
id?: string;
loader?: LoaderFunction;
action?: ActionFunction;
element?: React.ReactNode | null;
Component?: React.ComponentType | null;
errorElement?: React.ReactNode | null;
ErrorBoundary?: React.ComponentType | null;
handle?: RouteHandle;
shouldRevalidate?: ShouldRevalidateFunction;
lazy?: LazyRouteFunction<RouteObject>;
}
// Path types
interface Path {
pathname?: string;
search?: string;
hash?: string;
}
interface Location extends Path {
state: any;
key: string;
}
// Pattern matching types
interface PathPattern {
path: string;
caseSensitive?: boolean;
end?: boolean;
}
interface PathMatch {
params: Params;
pathname: string;
pathnameBase: string;
pattern: PathPattern;
}
interface RouteMatch {
params: Params;
pathname: string;
pathnameBase: string;
route: RouteObject;
}
// Utility types
type Params = Record<string, string | number>;
type To = string | Partial<Path>;
type InitialEntry = string | Partial<Location>;
// Error types
interface ErrorResponse {
status: number;
statusText: string;
data: any;
}
// Function types
type LoaderFunction = (args: LoaderFunctionArgs) => Promise<Response> | Response | Promise<any> | any;
type ActionFunction = (args: ActionFunctionArgs) => Promise<Response> | Response | Promise<any> | any;Install with Tessl CLI
npx tessl i tessl/npm-react-router-native