DEV Community

Prasanth React
Prasanth React

Posted on

🧭 React Router Too Verbose? Try This: File-Based Routing like Next.js β€” In Any React App!

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)
Enter fullscreen mode Exit fullscreen mode

πŸš€ Usage

Example src/app/page.jsx:

export default function Home({ data }) {
  return <h1>Home Page {data && <span>{data.message}</span>}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Example src/app/layout.jsx:

export default function RootLayout({ children }) {
  return (
    <div>
      <header>Header Content</header>
      <main>{children}</main>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 };
}
Enter fullscreen mode Exit fullscreen mode

Example src/App.jsx:

import { AppRouter } from "react-next-router";

function App() {
  return <AppRouter />;
}
export default App;
Enter fullscreen mode Exit fullscreen mode

πŸ“Ž Links

Top comments (0)