React Router in Vite: Step-by-Step Setup for Navigation

One of the first things you’ll need when creating single-page applications is page navigation. React Router in Vite is quick, simple, and clean to set up if you’re using it for your React application. It allows you to switch between different pages without reloading, making your app feel smooth and seamless. With just a few configuration steps, you can have dynamic routing up and running in no time.

This comprehensive tutorial will show you how to incorporate it for seamless client-side navigation into your Vite-powered application. Now let’s get started!


Why Use React Router in Vite?

The industry standard for routing in React apps is React Router. It makes it possible to switch between pages without having to restart the browser. A developer’s dream is to combine Vite’s lightning-fast builds and hot reloads.


Step 1: Install React Router DOM

Open your terminal and run:

yarn add react-router-dom
# or
npm install react-router-dom

React Router DOM is the core library for client-side routing in React.


Step 2: Set Up Basic Folder and File Structure

To keep things tidy, let’s create a pages folder:

src/
├── pages/
│   ├── Home.tsx
│   └── About.tsx
├── App.tsx
└── main.tsx

Inside Home.tsx:

const Home = () => <h2>Welcome to the Home Page</h2>;
export default Home;

And About.tsx:

const About = () => <h2>This is the About Page</h2>;
export default About;

Step 3: Add React Router Setup in App.tsx

Import the necessary components and wrap your routes:

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';

function App() {
  return (
    <Router>
      <nav className="space-x-4 p-4">
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

export default App;

Pro Tip: Wrap your entire routing logic inside BrowserRouter for full navigation functionality.


Step 4: Render App in main.tsx

Ensure your router is part of the rendered tree:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

And that’s it! You’ve now added React Router in Vite smoothly.


External Resources


Internal Resources


Final Thoughts

One of the greatest choices for creating scalable, quick, and fluid single-page apps is to integrate React Router into Vite. Navigation is an essential component of any project, whether you’re building a full-stack dashboard or a portfolio.

Now that you’ve added routing, where will you go next?

Try adding nested routes, route guards, or animated transitions using Framer Motion. The road ahead is full of possibilities.

Share this post