mouter-router
v0.0.6
Published
A lightweight, fully-typed, and developer-friendly routing library for React applications. Built from scratch keeping simplicity and performance in mind.
Readme
mouter-router 🛤️
A lightweight, fully-typed, and developer-friendly routing library for React applications. Built from scratch keeping simplicity and performance in mind.
Powered by path-to-regexp to support complex parametric routes seamlessly.
Features ✨
- Minimalist & Fast: Zero bloat, focusing only on what matters.
- Parametric Routes: Dynamically match routes with parameters (e.g.,
/user/:id). - Flexible Configuration: Define your routes using declarative JSX/TSX (
<Route />) or an array configuration. - Type Safe: Fully written in TypeScript for excellent autocomplete and type inference.
- No Dependencies: Relies solely on
Reactas a peer dependency andpath-to-regexpfor URL resolution.
Installation 📦
Install mouter-router alongside its peer dependencies using your preferred package manager:
# Using npm
npm install mouter-router
# Using pnpm
pnpm add mouter-router
# Using yarn
yarn add mouter-routerUsage 🚀
1. Array Configuration (Configuration Object Pattern)
You can pass an array of routes directly to the <Router /> component for a centralized configuration:
import { Router } from 'mouter-router';
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/search/:term', component: Search }, // Parametric route
];
export default function App() {
return (
<Router
routes={routes}
defaultComponent={NotFound}
/>
);
}2. Declarative Usage (React Components Pattern)
If you prefer a more declarative approach similar to React Router, you can use the <Route /> component as children:
import { Router, Route } from 'mouter-router';
import Home from './pages/Home';
import Profile from './pages/Profile';
import NotFound from './pages/NotFound';
export default function App() {
return (
<Router defaultComponent={NotFound}>
<Route path="/" component={Home} />
<Route path="/profile/:username" component={Profile} />
</Router>
);
}Accessing Route Parameters
When navigating to parametric routes (e.g., /profile/:username), the matched parameters are seamlessly injected into your component via the params prop:
// pages/Profile.tsx
interface ProfileProps {
params?: Record<string, string>;
}
export default function Profile({ params }: ProfileProps) {
return (
<div>
<h1>User Profile</h1>
<p>Hello, {params?.username}!</p>
</div>
);
}Navigation using <Link />
Use the <Link /> component instead of native <a> tags to navigate directly without refreshing the entire page. It fully supports target="_blank" and native CMD/CTRL + Click behaviors!
import { Link } from 'mouter-router';
export default function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About Us</Link>
<Link to="/contact" target="_blank">Contact</Link>
</nav>
);
}Programmatic Navigation
To navigate imperatively from inside event handlers (like button clicks or form submissions), use the exported navigate() function:
import { navigate, getCurrentPath } from 'mouter-router';
export default function SubmitButton() {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Do some logic...
console.log("Current path is:", getCurrentPath());
// Imperatively redirect to another page
navigate('/success');
};
return <button onClick={handleSubmit}>Submit Form</button>;
}API Reference 📚
Components
<Router />
The main wrapper that handles URL state and renders the matched route.
routes: Optional. An array of{ path: string, component: React.ComponentType }objects.defaultComponent: Optional. A React component to render when no routes match a 404 handler.children: Optional.<Route />components for declarative usage.
<Route />
A dummy component used functionally by <Router /> to declare route boundaries.
path: The string path representing the route (/,/about,/users/:id).component: The React component to render when the path matches.
<Link />
An accessible anchor tag wrapper intended for SPA navigation.
to: The local path you want to navigate to.- Accepts all standard
HTMLAnchorElementattributes (className,target, etc.).
Utilities
navigate(href: string)
Replaces window.history.pushState under the hood and triggers a fast re-render of the Router without destroying React state or reloading the entire page.
getCurrentPath()
Returns the value of globalThis.location.pathname.
subscribeToNavigation(callback: Function)
Primitive event listener binder for hooking into popstate and internal push events. Mostly used under the hood by the router engine.
License 📜
MIT
