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

@tomkoooo/t-router

v1.1.0

Published

---

Downloads

795

Readme


t-router

t-router is a dynamic routing library for React with Vite, designed to handle routes dynamically based on your file structure, with the option to apply middleware for route protection or other logic. It supports both TypeScript and JavaScript files and integrates seamlessly with React Router.

Installation

To use t-router in your project, you can install it via npm or yarn.

Using npm:

npm install @tomkoooo/t-router

Using yarn:

yarn add @tomkoooo/t-router

Usage

Basic Setup

import React from 'react';
import { DynamicRouter, Link } from '@tomkoooo/t-router';

const App = () => {
  const pagesConfig = {
    '/home': {
      type: 'public'
    },
    '/profile': {
      type: 'private',
      credentials: 'user.role === "admin"',
      redirectTo: '/login'
    }
  };
  /*
   or use import routes './your-route-config.json'

    {
      "Routes" : {
        "/": {
          "type": "public"
        }
      }
    }

  <DynamicRouter pagesConfig={routes.Routes} pages={pages}/>
  */

   const pages = import.meta.glob('./pages/**/*.{tsx,jsx}') //Needs to be passed like this because from node_modules the package ahs no access for glob but this creates opportunitys to use it outside Vite

  return (
    <DynamicRouter pagesConfig={pagesConfig} pages={pages}/>
    {/*There is a built-in middlewere by default that handles the pagesConfig logic, by default every route will be public, but for the user credentials to work you need to pass a user object*/}
  );
};

export default App;

Dynamic Routing

t-router uses import.meta.glob to dynamically import your pages based on the file structure but you need to call the glob function and pass the reasult as pages because it's impossible to do from node_modules folder. Files should be placed under the pages directory and named page.js, page.jsx, page.ts, or page.tsx. For the root create a page file in the root of the pages directory and it will match the / route.

Example file structure:

src/
  pages/
    home/
      page.tsx
    profile/
      page.tsx
    [id]/
      page.tsx
   page.tsx

The router will automatically pick up these routes and map them to the URL paths /home and /profile. And also can handle dynamic routes like [id] or [name].

Dynamic Pages

Create dynamic URls with braces. The router automaticly handles them and you can access the param in the component like this:

// src/pages/blog/[id]/page.tsx
import React from 'react';
import { useDynamicParams } from '@tomkoooo/t-router';

const BlogPostPage: React.FC = () => {
  const { id } = useDynamicParams(); //you need to use the dynamic name you given in the braces

  return <h1>Blog Post ID: {id}</h1>;
};

export default BlogPostPage;

Custom Middleware

You can pass a custom middleware component to the DynamicRouter.

import { DynamicRouter, Link } from '@tomkoooo/t-router';
import MyCustomMiddleware from './MyCustomMiddleware';
import routes from './routes.json'

const App = () => {

  const pages = import.meta.glob('./pages/**/*.{tsx,jsx}')

  return (
    <DynamicRouter pagesConfig={routes.Routes} pages={pages} middlewere={MyCustomMiddleware}/>
  );
};

export default App;

Custom User Object

You can pass a custom user object to the router, which can be used for route authentication.

const App = () => {
  const user = {
    id: '1',
    name: 'John Doe',
    role: 'admin'
  };

  return (
    <DynamicRouter pagesConfig={pagesConfig} pages={pages} user={user}/>
    {/*You can pass user object for the built-in middlewere to work with it for private routing*/}
  );
};

Link Component

t-router provides a custom Link component that works with React Router and supports passing additional props like className and target.

import { Link } from '@tomkoooo/t-router';

const MyComponent = () => {
  return (
    <div>
      <Link to="/profile" className="nav-link">
        Go to Profile
      </Link>
    </div>
  );
};

NotFound Page

t-router includes a default NotFound page that automatically handles 404 errors on the router but can be imported.

import NotFound from '@tomkoooo/t-router/dist/pages/NotFound';

const App = () => {
  return (
      <NotFound />
  );
};

API

DynamicRouter

  • pages (required): All the pages in the pages folder.

  • pagesConfig (required): An object defining routes and their configurations. Each route can have a type, optional credentials condition, and a redirectTo URL.

  • user (optional): A custom user object to be passed for route authentication.

  • middlewere (optional): A custom middleware component to handle additional logic such as authentication or redirects.

  • loadingFallback (optional): A fallback element displayed while the route components are loading.

Link

  • to (required): The path to navigate to.
  • children (required): The content displayed inside the link.
  • className (optional): Additional CSS class for styling.
  • target (optional): The target for opening the link (e.g., _blank).

License

This project is licensed under the MIT License.


Let me know if you need further adjustments! Github/Tomkoooo