@biggerpixel/ts-route-kit
TypeScript icon, indicating that this package has built-in type declarations

0.10.0 • Public • Published

Route Kit

A type-safe route helper

Installation

npm install @biggerpixel/ts-route-kit

Usage

Create a RouteKit

import { createRoute } from '@biggerpixel/ts-route-kit';

export const RouteKit = {
    Home: createRoute('/'),
    ArticleList: createRoute('/articles'),
    ArticleDetail: createRoute('/articles/<int:id>'),
};

Create a RouteLink component

import { createRoute, RouteLinkerParams } from '@biggerpixel/ts-route-kit';
import Link from 'next/link';
import { ComponentProps } from 'react';

/**
 * Create a RouteLink component that can be used to create links to routes in a type safe way
 * @param routeKit - The route kit to use
 * @returns A RouteLink component
 * @example
 * const { RouteLink } = createRouteLink(RouteKit);
 *
 * <RouteLink to="articleList" />;
 * <RouteLink to="articleDetail" params={{ id: 2 }} />;
 */
export const RouteLink = <K extends keyof typeof RouteKit>({
    to,
    ...props
}: {
    to: K;
} & RouteLinkerParams<Parameters<(typeof RouteKit)[K]>[0]> &
    Omit<ComponentProps<typeof Link>, 'href'>) => {
    const routeParams = ('params' in props ? props.params : {}) as any;
    return <Link href={RouteKit[to](routeParams)} {...props} />;
};

Use the RouteLink component in your project

// Use in your components like:
<RouteLink to="ArticleDetail" params={{ id: 123 }}>
    Your Link
</RouteLink>

Readme

Keywords

none

Package Sidebar

Install

npm i @biggerpixel/ts-route-kit

Weekly Downloads

0

Version

0.10.0

License

MIT

Unpacked Size

13.3 kB

Total Files

19

Last publish

Collaborators

  • simonalmers