Reactβs flexibility is powerful β but when it comes to routing, things can quickly get verbose. If you love how Next.js App Router handles file-based routing, nested layouts, and grouped routes, Iβve got something exciting:
Meet
react-next-router
β a plug-and-play file-based routing system for React that mimics Next.js App Router behavior β but for any React app!
π Features
- β Next.js App Router-like routing in React apps
- β Auto-load pages from the /app folder
- β
Support for Layouts via
layout.jsx
- β Route Groups with (group) folders
- β
Dynamic routes with
[slug], [...slug], [[slug]]
- β
Error boundaries via
error.jsx
- β
404 Not Found handling with
404.jsx
- β
Loader support for data fetching
loader.jsx
- β Fully type-safe (TypeScript supported)
src/
βββ app/
βββ layout.jsx # Root layout
βββ page.jsx # Index route ('/')
βββ about/
β βββ page.jsx # '/about'
βββ blog/
β βββ [slug]/
β β βββ page.jsx # '/blog/:slug'
β β βββ loader.jsx # Loader for data fetching
β βββ layout.jsx # Layout for '/blog/*'
βββ (admin)/
β βββ dashboard/
β β βββ page.jsx # '/dashboard'
β βββ layout.jsx # Layout for group
βββ error.jsx # Error boundary
βββ 404.jsx # Not Found page
βββ loading.jsx # Loading component (renders while loading)
π Usage
Example src/app/page.jsx:
export default function Home({ data }) {
return <h1>Home Page {data && <span>{data.message}</span>}</h1>;
}
Example src/app/layout.jsx:
export default function RootLayout({ children }) {
return (
<div>
<header>Header Content</header>
<main>{children}</main>
</div>
);
}
Example src/app/loader.jsx:
// This loader runs before the sibling page.jsx and its return value is passed as the 'data' prop
export default async function loader() {
// You can fetch from any API or return any data
const res = await fetch("https://api.example.com/message");
const data = await res.json();
return { message: data.message };
}
Example src/App.jsx:
import { AppRouter } from "react-next-router";
function App() {
return <AppRouter />;
}
export default App;
π Links
- π NPM: react-next-router
- π§ GitHub: github.com/prasanthreact/react-next-router
- π¦ Demo: StackBlitz Example
Top comments (0)