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:
$ npm install @granite-js/plugin-router --save-dev$ pnpm add @granite-js/plugin-router --save-dev$ yarn add @granite-js/plugin-router --devThe 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.
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.
$ npx granite dev$ pnpm granite dev$ yarn granite devFor example, if you add a pages/page-a.tsx file, the following screen component and routing code will be automatically generated:
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.
// 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 RegisterScreenInput {
'/page-a': (typeof _PageARoute)['_inputType'];
'/page-b': (typeof _PageBRoute)['_inputType'];
'/page-c': (typeof _PageCRoute)['_inputType'];
}
interface RegisterScreen {
'/page-a': (typeof _PageARoute)['_outputType'];
'/page-b': (typeof _PageBRoute)['_outputType'];
'/page-c': (typeof _PageCRoute)['_outputType'];
}
}Using these automatically generated type definitions makes routing safer and helps reduce mistakes.