DEV Community

Joshua Amaju
Joshua Amaju

Posted on

File-based routing: Vite + react-router-dom + generouted

Getting started

npm create vite@latest my-app -- --template react
Enter fullscreen mode Exit fullscreen mode
cd my-app
npm i

npm i react-router-dom @generouted/react-router
Enter fullscreen mode Exit fullscreen mode

Setup

// vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import generouted from '@generouted/react-router/plugin'

export default defineConfig({
  plugins: [react(), generouted()]
})
Enter fullscreen mode Exit fullscreen mode

Create the entry point

cd src
touch main.tsx
Enter fullscreen mode Exit fullscreen mode
// src/main.tsx

import { createRoot } from 'react-dom/client'
import { Routes } from '@generouted/react-router'

createRoot(document.getElementById('root')!).render(<Routes />)
Enter fullscreen mode Exit fullscreen mode

Pages

Pages/routes go in the src/pages directory

// src/pages/index.tsx
export default function Home() {
  return <h1>Home</h1>
}
Enter fullscreen mode Exit fullscreen mode

Loaders/Actions

// src/pages/users.tsx

export function Loader() {
  // ...
  return { /* your data */ }
}

export function Action({ request }: ActionFunctionArgs) {
  // ...
}

export default function Users() {
  return <h1>List of users</h1>
}
Enter fullscreen mode Exit fullscreen mode

Actions/Loaders are case sensitive, always use Loader, Action

Due to a bug, actions are not supported in index routes i.e pages with src/pages/users/index.tsx or src/pages/projects/[id]/index.tsx. To use actions the page must not be named index.{(j|t)xs}

Links

https://github.com/oedotme/generouted
https://reactrouter.com/en/main
https://vitejs.dev/guide/

Top comments (0)