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.
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).
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.
To get started, let's create a new Vite project with React Router:
npm install -g vitevite create vite-router-appcd vite-router-appnpm install react-router-domNow that we have everything set up, let's explore the basics of 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:
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.
Always use the exact prop on your default route to ensure that it matches the exact path and not any subroutes.
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.
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.
The useHistory hook is available in the react-router-dom package.
Nested routes allow us to create complex multi-level routing structures. Here's an example of a nested route:
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.
When working with nested routes, make sure to wrap the nested routes within the parent route.
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:
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.
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.
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! 🚀💻