Skip to content

Router Plugin

Granite Router is a type-safe router that supports file-based routing and automatically assigns types for each path. You can create screens simply by adding files to the pages/ directory.

To easily create and manage pages, install the plugin as shown below:

sh
$ npm install @granite-js/plugin-router --save-dev
sh
$ pnpm add @granite-js/plugin-router --save-dev
sh
$ yarn add @granite-js/plugin-router --dev

The following is an example of adding the router plugin to the granite.config.ts configuration. This plugin automatically creates routes based on the pages/ folder.

ts
import { env } from '@granite-js/plugin-env';
import { hermes } from '@granite-js/plugin-hermes';
import { router } from '@granite-js/plugin-router';
import { defineConfig } from '@granite-js/react-native/config';

export default defineConfig({
  /**
   * granite://example
   */
  scheme: 'granite',
  appName: 'example',
  plugins: [
    router(), 
  ],
});

Development Mode

In development mode, when you create a new page file, the screen component code and type definitions are automatically generated.

sh
$ npx granite dev
sh
$ pnpm granite dev
sh
$ yarn granite dev

For example, if you add a pages/page-a.tsx file, the following screen component and routing code will be automatically generated:

tsx
import React from 'react';
import { Text, View } from 'react-native';
import { createRoute } from '@granite-js/react-native';

export const Route = createRoute('/page-a', {
  validateParams: (params) => params,
  component: PageA,
});

function PageA() {
  return (
    <View>
      <Text>Hello PageA</Text>
    </View>
  );
}

This page can be accessed via the granite://example/page-a path.

Automatically Generated Type Definitions

Granite also automatically defines types for routing paths. Thanks to this, it will generate an error if the path or parameters are incorrect when routing.

tsx
// src/router.gen.ts

/* eslint-disable */
// This file is auto-generated by @granite-js/react-native. DO NOT EDIT.
import { Route as _PageARoute } from '../pages/page-a';
import { Route as _PageBRoute } from '../pages/page-b';
import { Route as _PageCRoute } from '../pages/page-c';

declare module '@granite-js/react-native' {
  interface RegisterScreen {
    '/page-a': ReturnType<typeof _PageARoute.useParams>;
    '/page-b': ReturnType<typeof _PageBRoute.useParams>;
    '/page-c': ReturnType<typeof _PageCRoute.useParams>;
  }
}

Using these automatically generated type definitions makes routing safer and helps reduce mistakes.