React Router with Vite: Navigate Through Your React Applications

beginner
7 min

React Router with Vite: Navigate Through Your React Applications

Welcome to our comprehensive guide on using React Router in your Vite projects! In this tutorial, we'll learn how to create multi-page applications using React Router, and navigate between different pages smoothly. By the end of this lesson, you'll have a solid understanding of how to structure your Vite-based React applications and manage routing effectively.

Let's start by understanding why we need React Router and what it does.

🎯 What is React Router?

React Router is a popular routing library for React applications. It helps you to manage different routes and URLs in your application, allowing users to navigate between different pages. React Router is essential for creating single-page applications (SPAs) and multi-page applications (MPAs).

📝 Note:

Before diving into React Router, make sure you have a basic understanding of React, JavaScript, and Vite. If you're not familiar with these concepts, we recommend checking out our previous tutorials on React and Vite.

Setting up a New Vite Project with React Router

To get started, let's create a new Vite project with React Router:

  1. Install Vite globally:
bash
npm install -g vite
  1. Create a new project:
bash
vite create vite-router-app
  1. Navigate to the project directory:
bash
cd vite-router-app
  1. Install React Router:
bash
npm install react-router-dom

Now that we have everything set up, let's explore the basics of React Router.

🎯 Creating Routes in React Router

In React Router, we define routes using Route components and navigate between them using Link components. Here's a simple example of a two-page application:

jsx
import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const HomePage = () => <div>Welcome to the Home Page!</div>; const AboutPage = () => <div>About Us</div>; function App() { return ( <Router> <div> <Link to="/">Home</Link> <Link to="/about">About</Link> <Route path="/" exact component={HomePage} /> <Route path="/about" component={AboutPage} /> </div> </Router> ); } export default App;

In this example, we've created two pages (HomePage and AboutPage) and defined routes for them using the Route component. The Link components allow users to navigate between pages.

💡 Pro Tip:

Always use the exact prop on your default route to ensure that it matches the exact path and not any subroutes.

Navigating Programmatically

Sometimes, we might need to navigate programmatically, such as when a user clicks a button or submits a form. React Router provides the useHistory hook for this purpose.

jsx
import { useHistory } from 'react-router-dom'; function About() { let history = useHistory(); const handleClick = () => { history.push('/'); }; return ( <div> <p>About Us</p> <button onClick={handleClick}>Go to Home</button> </div> ); }

In this example, we've used the useHistory hook to access the history object and programmatically navigate to the home page when the button is clicked.

📝 Note:

The useHistory hook is available in the react-router-dom package.

Nested Routes

Nested routes allow us to create complex multi-level routing structures. Here's an example of a nested route:

jsx
import React from 'react'; import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'; const HomePage = () => <div>Welcome to the Home Page!</div>; const AboutPage = () => <div>About Us</div>; const ServicesPage = () => <div>Our Services</div>; const App = () => ( <Router> <div> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/services">Services</Link> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/about" component={AboutPage} /> <Route path="/services" component={() => <ServicesPage />}> <Route path="subpage" component={() => <div>Subpage</div>} /> </Route> </Switch> </div> </Router> ); export default App;

In this example, we've created a nested route for the /services page, which includes a subroute (/services/subpage). The Switch component is used to ensure that only one Route matches at a time.

💡 Pro Tip:

When working with nested routes, make sure to wrap the nested routes within the parent route.

Private Routes

Private routes allow us to protect certain pages and ensure that only authenticated users can access them. Here's an example of a private route:

jsx
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => localStorage.getItem('token') ? ( <Component {...props} /> ) : ( <Redirect to="/login" /> ) } /> ); // Usage <PrivateRoute component={AboutPage} />

In this example, we've created a PrivateRoute component that checks for a token in local storage before rendering the protected component. If no token is found, the user is redirected to the login page.

📝 Note:

This example assumes that you're storing the token in local storage. In a real-world application, you should use a more secure method such as JWT tokens.

Quick Quiz
Question 1 of 1

What is the purpose of the `exact` prop in the `Route` component?

That's it for our React Router with Vite tutorial! We hope you enjoyed learning and that you're now comfortable navigating through your React applications using React Router. Happy coding! 🚀💻