swan-io / chicane

A simple and safe router for React and TypeScript.
https://swan-io.github.io/chicane/
MIT License
383 stars 9 forks source link
react router typescript
@swan-io/chicane logo

@swan-io/chicane

mit licence npm version bundlephobia

A simple and safe router for React and TypeScript.

Design principles

Installation

$ yarn add @swan-io/chicane
# --- or ---
$ npm install --save @swan-io/chicane

Links

Quickstart

import { createRouter } from "@swan-io/chicane";
import { match } from "ts-pattern";

const Router = createRouter({
  Home: "/",
  Users: "/users",
  User: "/users/:userId",
});

const App = () => {
  const route = Router.useRoute(["Home", "Users", "User"]);

  // route object is a discriminated union
  return match(route)
    .with({ name: "Home" }, () => <h1>Home</h1>)
    .with({ name: "Users" }, () => <h1>Users</h1>)
    .with({ name: "User" }, ({ params }) => <h1>User {params.userId}</h1>) // params are strongly typed
    .otherwise(() => <h1>404</h1>);
};

Run the example app

$ git clone git@github.com:swan-io/chicane.git
$ cd chicane/example

$ yarn install && yarn dev
# --- or ---
$ npm install && npm run dev

🙌 Acknowledgements