How to Install React Router in a Vite Project

Modern front-end development often demands highly interactive applications, and routing plays a critical role in structuring such interfaces. One common challenge developers face when starting a new React project with Vite is properly setting up React Router for smooth client-side navigation. Without it, managing dynamic routes, protected pages, and nested layouts becomes increasingly difficult as the app scales.

Project Initialization

Starting with a clean Vite project ensures minimal friction when adding routing. Vite, known for its fast build times and optimized development environment, is already equipped to support React through its official template. Here’s a quick setup:

npm create vite@latest my-app -- --template react
cd my-app
npm install

Once the project is scaffolded and dependencies are installed, the next step involves integrating routing logic.

Installing Dependencies

React Router is not bundled with React by default. For React Router v6, which is currently the stable version, installing react-router-dom is essential.

npm install react-router-dom

This package provides the tools needed for route configuration, navigation, URL management, and even advanced features like lazy loading and route protection.

Configuring Basic Routes

With the router installed, the application needs to wrap its core component with a router provider. Open main.jsx and make the following change:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

Using BrowserRouter ensures that the app uses HTML5 history API to manage routing. For developers coming from older versions, Switch has been replaced by Routes, which you’ll use in the next step.

Creating Route Structure

Define your application’s routes inside App.jsx. The basic structure looks like this:

import { Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import About from './pages/About'

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
    </Routes>
  )
}

export default App

Each Route maps a path to a component. The element prop now directly receives the JSX element, a cleaner approach introduced in version 6. This pattern encourages modular route definitions, making it easier to scale as more pages are added.

Handling 404 Pages

Missing route handling is a subtle aspect often ignored initially but crucial for a polished user experience. React Router makes this straightforward:

<Route path="*" element={<h1>404 - Page Not Found</h1>} />

This wildcard route should always be at the bottom, ensuring it only renders when no other route matches.

More insights about creating better 404 UX can be explored in the article on custom 404 pages in React.

Folder Structure Recommendation

As your application grows, organizing routes and pages clearly becomes necessary. A suggested structure:

Folder/FilePurpose
/pages/Individual route components
App.jsxRoute definitions
main.jsxRouter setup entry point

A nested structure like this allows route-level code splitting and better component encapsulation. Combining this approach with dynamic routing can simplify even complex navigational flows.

Adding Navigation

Routing without navigation leads to a jarring user experience. Use Link or NavLink for seamless client-side navigation:

import { Link } from 'react-router-dom'

<nav>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>
</nav>

Compared to traditional <a> tags, these React components prevent full-page reloads, preserving app state and offering a snappier interaction.

Common Issues and Fixes

One frequent misstep is deploying a Vite + React Router app on platforms like GitHub Pages or Netlify without configuring the index.html fallback. React Router relies on client-side routing, which means non-root paths like /about must also be served via index.html.

To handle this:

  • For Netlify, use a _redirects file with: /* /index.html 200
  • For GitHub Pages, consider using HashRouter instead of BrowserRouter or configure a proper 404.html fallback.

This is also where understanding BrowserRouter becomes vital—it determines how the URL is interpreted and rendered.

Conclusion

Integrating React Router in a Vite project might seem like an extra layer during initial development, but skipping it often leads to tight coupling of components and poor user navigation. By systematically installing, configuring, and organizing your routes, you lay a strong foundation for scalable and maintainable front-end architecture.

As your app evolves, the routing logic will often demand enhancements—like protected routes, dynamic segments, or query parameter handling. Each of these topics offers a deeper layer of flexibility that React Router handles gracefully, and some of these advanced concepts are already explored in topics like query parameters in React Router or creating protected routes. Starting right ensures these enhancements become easy additions—not painful rewrites.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top