npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@shardbook/react-router

v1.4.0

Published

Simple web router for react that supports nested routes, data loaders and inline imports for code-splitting.

Downloads

10

Readme

react-router · GitHub license Published on NPM Minified size Tree-shakeable

Simple web router for react that supports nested routes, data loaders and inline imports for code-splitting.

Examples

Using React.Supense and React.lazy

import { ComponentType, ComponentProps, lazy, Suspense } from "react";
import { RouterProvider, Outlet, Route } from "@shardbook/react-router";
import { Spinner } from "./Spinner";

// lazy loader function
function lazyLoad<T extends ComponentType<any>>(factory: () => Promise<{ default: T; }>) {
    const Component = lazy(factory);
    return (props: ComponentProps<T>) => (
        <Suspense fallback={<Spinner />}>
            <Component {...props} />
        </Suspense>
    );
}

const SignIn = lazyLoad(() => import("./SignIn"));
const SignUp = lazyLoad(() => import("./SignUp"));
const PageNotFound = lazyLoad(() => import("./PageNotFound"));
const PageError = lazyLoad(() => import("./PageError"));

const routes: Route[] = [
    {
        path: "/",
        element: <SignIn />,
    },
    {
        path: "/sign-up",
        element: <SignUp />,
    }
];

export default function App() {
    return (
        <RouterProvider
            routes={routes}
            noMatch={<PageNotFound />}
            error={(error) => <PageError error={error} />}
        >
            <Outlet setLocation fallback={<Spinner />} />
        </RouterProvider>
    );
}

It is always a good idea to wrap a lazy component inside a Suspense to let the user know that we're still importing it.

Using inline import

import { RouterProvider, Outlet, Route } from "@shardbook/react-router";
import { Spinner } from "./Spinner";

const PageNotFound = lazyLoad(() => import("./PageNotFound"));
const PageError = lazyLoad(() => import("./PageError"));

const routes: Route[] = [
    {
        path: "/",
        element: () => import("./SignIn"),
    },
    {
        path: "/sign-up",
        element: () => import("./SignUp"),
    }
];

export default function App() {
    return (
        <RouterProvider
            routes={routes}
            noMatch={<PageNotFound />}
            error={(error) => <PageError error={error} />}
        >
            <Outlet setLocation fallback={<Spinner />} />
        </RouterProvider>
    );
}

The router will import the component first before changing the location. You can use useRouter().loading to handle loading state.

With loader

// Dashboard.tsx
export default function Dashboard() {
    return <>Hello world!</>;
}

// User.tsx
export loader(config: any, params: any) {
    return fetch("/api/user" + params.userId, {
        headers: {
            "Authorization": "Bearer " + config.token
        }
    });
}

export default function User(props : { config: any; params: any; data: any; }) {
    return (
        <>
           config: {JSON.stringify(props.config)}
           userId: {props.params.userId}
           data: {JSON.stringify(props.data)}
        </>
    );
}

// Layout.tsx
import { Outlet, Link } from "@shardbook/react-router";
import { Spinner } from "./Spinner";

export default function Layout() {
    return (
        <>
            <header>
                <Link to="/">Dashboard</Link>
                <Link to="/my-user-id">User</Link>
            </header>

            <main>
                <Outlet setLocation fallback={<Spinner />} />
            </main>
        </>
    );
}

// App.tsx
import { RouterProvider, Route } from "@shardbook/react-router";

const PageNotFound = lazyLoad(() => import("./PageNotFound"));
const PageError = lazyLoad(() => import("./PageError"));

const routes: Route[] = [
    {
        path: "/",
        element: () => import("./Dashboard"),
    },
    {
        path: "/:userId",
        element: () => import("./User"),
    }
];

export default function App() {
    return (
        <RouterProvider
            routes={routes}
            noMatch={<PageNotFound />}
            error={(error) => <PageError error={error} />}
            config={{ token: "server-token" }}
        >
            <Layout />
        </RouterProvider>
    );
}

If your going to navigate to /my-user-id, the router will import the component with the loader first, then call the loader, waits for its response before changing the location. You can use useRouter().loading to handle loading state.

Components

  • RouterProvider - Routes controller.
  • Outlet - Route element renderer.
  • Link - A history-aware <a>.

Hooks

  • useRouter - Returns the current location and the loading path.
  • useNavigate - Returns an imperative function for route navigation.

Type declarations

type RouterProps = {
    /**
     * @required
     * An array of `Route` objects with nested routes on the `children`;
     */
    routes: Route[];
    /**
     * List of route path that the user can access;
     */
    access?: string[];
    /**
     * Configurations that will be pass down to routes and loaders.
     * 
     * Ex. Current user or user token.
     */
    config?: any,
    /**
     * This will be shown if there's no matching route of the current location.
     * @defaultValue "Not found"
     */
    noMatch?: React.ReactNode;
    /**
     * This will be shown if there's an error while loading route.
     */
    error?: (error: string) => React.ReactNode;
    /**
     * @required
     */
    children: React.ReactNode;
};
type Route = {
    /**
     * @required
     * Must have a trailing `/`.
     */
    path: string;
    /**
     * Route element.
     * 
     * Note: This will be ignored if this is a parent route.
     */
    element?: (() => Promise<{
        default: (props?: any) => JSX.Element;
        loader?: (config?: any, params?: any) => Promise<Response>;
    }>) | React.ReactNode;
    /**
     * Route children.
     */
    children?: Route[];
};
type LinkProps = {
    /**
     * Set to `true` to skip client side routing.
     */
    reloadDocument?: boolean;
    /**
     * Set to `true` to use `history.replace`.
     */
    replace?: boolean;
    /**
     * History state.
     */
    state?: any;
    /**
     * Pathname.
     */
    to: string;
} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href">;