Using React Router to Create a Multi-Page Application
Learn how to use React Router to create a multi-page application, including setting up routes and navigating between pages.
Introduction to React Router
In this tutorial, we will learn how to use React Router to create a multi-page application. We will cover setting up routes and navigating between pages.
Step 1: Setting up the Project
First, we need to set up a new React project. We can do this by running the following command in our terminal:
npx create-react-app router-app
Step 2: Installing React Router
Next, we need to install React Router. We can do this by running the following command in our terminal:
npm install react-router-dom
Step 3: Creating the Routes
We can create a new component for our routes. We can do this by creating a new file called Routes.js in the src directory:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function Routes() {
return (
<BrowserRouter>
<div>
<nav>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/about'>About</Link></li>
<li><Link to='/contact'>Contact</Link></li>
</ul>
</nav>
<Route path='/' exact component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
</div>
</BrowserRouter>
);
}
export default Routes;
Step 4: Creating the Page Components
We can create new components for our pages. We can do this by creating new files called Home.js, About.js, and Contact.js in the src directory:
// Home.js
import React from 'react';
function Home() {
return (
<div>
<h1>Welcome to the home page!</h1>
</div>
);
}
export default Home;
// About.js
import React from 'react';
function About() {
return (
<div>
<h1>Welcome to the about page!</h1>
</div>
);
}
export default About;
// Contact.js
import React from 'react';
function Contact() {
return (
<div>
<h1>Welcome to the contact page!</h1>
</div>
);
}
;