Most React applications involve a routing setup to allow user navigation between different pages. There are two common ways to handle routing in React depending on your rendering method.
You probably know React Router, a widely used library for declarative/component-based client-side routing. With server-side rendering, React frameworks like Next.js offer an alternative approach called file-based routing.
In a traditional client-side React routing setup with React router, you'll declare your routes within a
<Switch /> component by adding a
<Route/> component for each page, specifying a path and a corresponding component to be rendered as a page. It works fine but it lacks universal convention. Also when declaring many routes it becomes hard to follow, at least in my experience.
With file-based routing you don't import page components manually. Instead you define all your routes by adding/removing/renaming files within a directory called
pages by convention. Each file inside the
pages directory will represent a route in your application. That makes it easier to visualize and manage as the
pages directory structure reflects all existing routes. You can also have dynamic routes with special file names and nested routes with sub-directories. We'll discuss some of the file-based routing common patterns shortly.
Today I want to share with you how I'm using React Router with Vite to build a file-based routing for client-side React applications inspired by Next.js file-based routing conventions, in 30 lines of code and one awesome Vite feature.