CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-router-native

Declarative routing for React Native applications with native-specific components and deep linking support

Pending
Overview
Eval results
Files

react-router-hooks.mddocs/

React Router Hooks

Complete re-export of React Router hooks for accessing navigation state, route data, and programmatic navigation in React Native applications.

Capabilities

Navigation Hooks

useNavigate

Returns a navigate function that lets you navigate programmatically, for example in an event handler or an effect.

/**
 * Returns a function for programmatic navigation
 * @returns NavigateFunction for programmatic navigation
 */
function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (to: To, options?: NavigateOptions): void;
  (delta: number): void;
}

interface NavigateOptions {
  replace?: boolean;
  state?: any;
  relative?: RelativeRoutingType;
}

useLocation

Returns the current location object, which represents the current URL.

/**
 * Returns the current location object
 * @returns Location object representing current URL
 */
function useLocation(): Location;

interface Location extends Path {
  state: any;
  key: string;
}

interface Path {
  pathname: string;
  search: string;
  hash: string;
}

useNavigationType

Returns the current navigation action which describes how the router came to the current location.

/**
 * Returns current navigation type
 * @returns NavigationType indicating how navigation occurred
 */
function useNavigationType(): NavigationType;

type NavigationType = "POP" | "PUSH" | "REPLACE";

Route Data Hooks

useParams

Returns an object of key/value pairs of URL parameters from the current route.

/**
 * Returns URL parameters from current route
 * @returns Object containing route parameters
 */
function useParams(): Params;

type Params = Record<string, string | undefined>;

useLoaderData

Returns the loader data from the current route.

/**
 * Returns loader data from current route
 * @returns Data returned by the route's loader function
 */
function useLoaderData(): unknown;

useActionData

Returns the action data from the current route.

/**
 * Returns action data from current route
 * @returns Data returned by the route's action function
 */
function useActionData(): unknown;

useRouteLoaderData

Returns the loader data for a specific route by ID.

/**
 * Returns loader data for specific route
 * @param routeId - ID of route to get data for
 * @returns Loader data for specified route
 */
function useRouteLoaderData(routeId: string): unknown;

Route Matching Hooks

useMatch

Returns match data about a route at the given path relative to the current location.

/**
 * Returns match data for a route pattern
 * @param pattern - Route pattern to match against
 * @returns PathMatch if pattern matches, null otherwise
 */
function useMatch(pattern: PathPattern): PathMatch | null;

interface PathMatch {
  params: Params;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}

useMatches

Returns the current route matches on the page.

/**
 * Returns all current route matches
 * @returns Array of UIMatch objects for current routes
 */
function useMatches(): UIMatch[];

interface UIMatch {
  id: string;
  pathname: string;
  params: Params;
  data: unknown;
  handle: unknown;
}

Utility Hooks

useHref

Returns a URL href for the given to value that may be used as the value of an <a href>.

/**
 * Returns href string for navigation target
 * @param to - Navigation target
 * @param options - Relative routing options
 * @returns String href for the target
 */
function useHref(to: To, options?: { relative?: RelativeRoutingType }): string;

useResolvedPath

Resolves the pathname of the location in the given to value against the pathname of the current location.

/**
 * Resolves path relative to current location
 * @param to - Path to resolve
 * @param relative - Relative routing type
 * @returns Resolved Path object
 */
function useResolvedPath(to: To, relative?: RelativeRoutingType): Path;

useInRouterContext

Returns true if the component is a descendant of a <Router>.

/**
 * Checks if component is inside a Router
 * @returns Boolean indicating router context presence
 */
function useInRouterContext(): boolean;

useOutlet

Returns the element for the child route at this level of the route hierarchy.

/**
 * Returns child route element
 * @param context - Context to pass to child routes
 * @returns React element for child route
 */
function useOutlet(context?: unknown): React.ReactElement | null;

useOutletContext

Returns the context (if provided) for the child route at this level of the route hierarchy.

/**
 * Returns outlet context from parent route
 * @returns Context object from parent route
 */
function useOutletContext<Context = unknown>(): Context;

Advanced Hooks

useBlocker

Blocks navigation based on a condition. Useful for preventing navigation when there are unsaved changes.

/**
 * Blocks navigation conditionally
 * @param shouldBlock - Function or boolean determining if navigation should be blocked
 * @returns Blocker object with navigation state
 */
function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;

interface Blocker {
  state: "unblocked" | "blocked" | "proceeding";
  reset(): void;
  proceed(): void;
  location?: Location;
}

type BlockerFunction = (args: { currentLocation: Location; nextLocation: Location }) => boolean;

useNavigation

Returns the current navigation state: "idle", "loading", or "submitting".

/**
 * Returns current navigation state
 * @returns Navigation object with loading states
 */
function useNavigation(): Navigation;

interface Navigation {
  state: "idle" | "loading" | "submitting";
  location?: Location;
  formMethod?: string;
  formAction?: string;
  formEncType?: string;
  formData?: FormData;
}

useRevalidator

Returns a revalidator object for manually revalidating route loaders.

/**
 * Returns revalidator for manual data revalidation
 * @returns Revalidator object with revalidate function
 */
function useRevalidator(): Revalidator;

interface Revalidator {
  revalidate(): void;
  state: "idle" | "loading";
}

Error Handling Hooks

useRouteError

Returns the error from the current route if there is one.

/**
 * Returns route error if present
 * @returns Error object or unknown error
 */
function useRouteError(): unknown;

useAsyncError

Returns any pending async error.

/**
 * Returns pending async error
 * @returns Error object or undefined
 */
function useAsyncError(): unknown;

useAsyncValue

Returns the resolved value from the nearest ancestor Await component.

/**
 * Returns resolved value from ancestor Await
 * @returns Resolved async value
 */
function useAsyncValue(): unknown;

Route Definition Hook

useRoutes

A hook equivalent of the <Routes> component for programmatic route definition.

/**
 * Programmatically define routes
 * @param routes - Array of route objects
 * @param locationArg - Optional location override
 * @returns React element for matching route
 */
function useRoutes(
  routes: RouteObject[],
  locationArg?: Partial<Location> | string
): React.ReactElement | null;

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>;
}

Usage Examples

Basic Navigation

import { useNavigate, useLocation, useParams } from "react-router-native";
import { TouchableOpacity, Text, View } from "react-native";

function ProductDetail() {
  const navigate = useNavigate();
  const location = useLocation();
  const { id } = useParams();
  
  const goBack = () => {
    navigate(-1); // Go back one step in history
  };
  
  const goToEdit = () => {
    navigate(`/products/${id}/edit`, {
      state: { from: location.pathname }
    });
  };
  
  return (
    <View>
      <Text>Product ID: {id}</Text>
      <TouchableOpacity onPress={goBack}>
        <Text>Back</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={goToEdit}>
        <Text>Edit Product</Text>
      </TouchableOpacity>
    </View>
  );
}

Data Loading

import { useLoaderData, useNavigation, useRevalidator } from "react-router-native";

function ProductList() {
  const products = useLoaderData() as Product[];
  const navigation = useNavigation();
  const revalidator = useRevalidator();
  
  const isLoading = navigation.state === "loading" || revalidator.state === "loading";
  
  const refreshData = () => {
    revalidator.revalidate();
  };
  
  return (
    <View>
      {isLoading && <Text>Loading...</Text>}
      {products.map(product => (
        <View key={product.id}>
          <Text>{product.name}</Text>
        </View>
      ))}
      <TouchableOpacity onPress={refreshData}>
        <Text>Refresh</Text>
      </TouchableOpacity>
    </View>
  );
}

Form Handling with Navigation Blocking

import { useBlocker, useNavigate } from "react-router-native";
import { useState } from "react";

function EditForm() {
  const [formData, setFormData] = useState({ name: "", description: "" });
  const [isDirty, setIsDirty] = useState(false);
  const navigate = useNavigate();
  
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      isDirty && currentLocation.pathname !== nextLocation.pathname
  );
  
  const handleSave = () => {
    // Save logic
    setIsDirty(false);
    navigate("/products");
  };
  
  const handleCancel = () => {
    if (isDirty) {
      // Show confirmation dialog
      if (confirm("You have unsaved changes. Are you sure?")) {
        navigate("/products");
      }
    } else {
      navigate("/products");
    }
  };
  
  // Handle blocked navigation
  if (blocker.state === "blocked") {
    return (
      <View>
        <Text>You have unsaved changes. Are you sure you want to leave?</Text>
        <TouchableOpacity onPress={blocker.proceed}>
          <Text>Yes, Leave</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={blocker.reset}>
          <Text>No, Stay</Text>
        </TouchableOpacity>
      </View>
    );
  }
  
  return (
    <View>
      {/* Form fields */}
      <TouchableOpacity onPress={handleSave}>
        <Text>Save</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={handleCancel}>
        <Text>Cancel</Text>
      </TouchableOpacity>
    </View>
  );
}

Error Handling

import { useRouteError } from "react-router-native";
import { View, Text } from "react-native";

function ErrorBoundary() {
  const error = useRouteError() as Error;
  
  return (
    <View>
      <Text>Something went wrong!</Text>
      <Text>{error.message}</Text>
    </View>
  );
}

Programmatic Route Definition

import { useRoutes } from "react-router-native";

function AppRoutes() {
  const routes = useRoutes([
    {
      path: "/",
      element: <Home />,
    },
    {
      path: "/products",
      element: <ProductLayout />,
      children: [
        { index: true, element: <ProductList /> },
        { path: ":id", element: <ProductDetail /> },
        { path: ":id/edit", element: <ProductEdit /> },
      ],
    },
  ]);
  
  return routes;
}

Types Summary

// Core types
type To = string | Partial<Path>;
type Params = Record<string, string | undefined>;
type RelativeRoutingType = "route" | "path";
type NavigationType = "POP" | "PUSH" | "REPLACE";

// Function types
type NavigateFunction = {
  (to: To, options?: NavigateOptions): void;
  (delta: number): void;
};

type BlockerFunction = (args: {
  currentLocation: Location;
  nextLocation: Location;
}) => boolean;

// Object types
interface Location extends Path {
  state: any;
  key: string;
}

interface Path {
  pathname: string;
  search: string;
  hash: string;
}

interface NavigateOptions {
  replace?: boolean;
  state?: any;
  relative?: RelativeRoutingType;
}

interface PathMatch {
  params: Params;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-react-router-native

docs

index.md

native-routing.md

navigation-hooks.md

react-router-components.md

react-router-hooks.md

react-router-utilities.md

search-parameters.md

tile.json