Mastering React Router: Create Dynamic Multi-page Web Apps
Table of Contents
- Introduction
- Setting up the React App
- Installing React Router Dom
- Creating the Pages and Components folders
- Building the Header Component
- Importing the Header Component into the Pages
- Creating the Home, About, and Contact Pages
- Importing the Pages into the App
- Configuring the Routes
- Handling Not Found Pages
- Conclusion
Introduction
In this tutorial, we will learn how to set up routing in a React app using React Router Dom. Routing allows us to have different pages on our Website and navigate between them seamlessly. We will Create multiple pages and components, and explore how to use them with React Router Dom to build a fully functional website.
Setting up the React App
Before we begin, make sure You have a React app set up. If you haven't done so already, follow the steps in the previous video to initialize the app and get everything ready for coding.
Installing React Router Dom
The first step in setting up routing in our React app is to install the React Router Dom Package. Open your terminal and navigate to your project directory. Run the following command to install React Router Dom:
npm install react-router-dom
Wait for the installation to complete, and then close the terminal.
Creating the Pages and Components folders
To organize our code, we will create two separate folders: pages
and components
. The pages
folder will contain our individual pages, while the components
folder will contain smaller components that make up those pages.
In your project's source directory, create a new folder called pages
. Similarly, create another folder called components
. This structure will help us distinguish between full-page components and smaller, reusable components within those pages.
Building the Header Component
Let's start by creating a simple header component. In the components
folder, create a new file called Header.js
. This header will serve as a common element across all pages.
In the Header.js
file, write the following code:
import React from 'react';
function Header() {
return <h1>Header - React Router Tutorial</h1>;
}
export default Header;
This code defines a functional component called Header
that returns a basic heading element. You can customize the content of the header as per your project requirements.
Importing the Header Component into the Pages
Now that our header component is ready, let's import it into our pages. Open the Home.js
, About.js
, and Contact.js
files inside the pages
folder.
In each of these files, import the Header
component using the following code:
import Header from '../components/Header';
Make sure to adjust the relative path to match the location of the Header.js
file from within the pages
folder.
Creating the Home, About, and Contact Pages
Next, let's create the three main pages of our app: Home, About, and Contact. Inside the pages
folder, create three new files: Home.js
, About.js
, and Contact.js
.
In each of these pages, write the following code:
import React from 'react';
import Header from '../components/Header';
function Home() {
return (
<div>
<Header />
<h2>Home Page</h2>
{/* Add content here */}
</div>
);
}
export default Home;
Replace the placeholder text with the appropriate content for each page. Feel free to customize the code and add more components as per your project's requirements.
Importing the Pages into the App
Now that our pages are ready, let's import them into the main App.js
file. Open the App.js
file and add the following imports at the top:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import NoPage from './pages/NoPage';
Make sure to adjust the relative paths Based on the location of the App.js
file. The NoPage
component will be used as a fallback for any routes that do not match.
Configuring the Routes
To set up the routes, wrap the entire content inside the return
statement of the App
component with a Router
component. This provides the necessary Context for routing.
Within the Router
component, add the following JSX code:
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={NoPage} />
</Switch>
</Router>
This code defines routes for the home page (/
), about page (/about
), and contact page (/contact
). The NoPage
component will be rendered if none of the defined routes match the Current URL.
Handling Not Found Pages
To display a custom "Not Found" page when a user enters an invalid URL, we need to create a NoPage
component. In the pages
folder, create a new file called NoPage.js
and add the following code:
import React from 'react';
function NoPage() {
return <h2>Error 404: Page Not Found</h2>;
}
export default NoPage;
Customize the error message as per your requirements.
Conclusion
Congratulations! You have successfully set up routing in your React app using React Router Dom. You can now navigate between different pages and customize the content of each page as needed.
Feel free to explore more advanced features of React Router Dom and experiment with different components and layouts to create a fully functional website. Enjoy building with React!
Highlights
- Set up routing in a React app using React Router Dom
- Create separate folders for pages and components
- Build a header component and import it into the pages
- Create home, about, and contact pages
- Import the pages into the main App component
- Configure routes using Router, Route, and Switch components
- Handle not found pages with a custom NoPage component
FAQ
Q: Can I have additional routes apart from home, about, and contact?
A: Yes, you can add as many routes as you need. Just create new components for each page you want to include and define the corresponding paths in the Route
components.
Q: How can I style the header and other components?
A: You can apply CSS styles to your components using inline styles, CSS modules, or external stylesheets. Choose the method that suits your project best.
Q: How do I add a nested route within one of the pages?
A: To create nested routes, you can define additional Route
components within the specific page component. This allows you to create a hierarchy of routes within a page.
Q: Are there any other routing libraries available for React?
A: Yes, besides React Router Dom, there are other routing libraries like Reach Router and Next.js that provide different features and capabilities. Choose the one that best fits your project requirements.
Q: Can I use React Router Dom in a React Native app?
A: No, React Router Dom is specifically designed for web applications. For routing in a React Native app, you can use libraries like React Navigation.
Q: Does React Router Dom support server-side rendering?
A: Yes, React Router Dom can be used for server-side rendering. It provides server-side routing support through libraries like React Router Config and React Router Sitemap.
Q: Is it necessary to include a "404 Not Found" page in my app?
A: It's a good practice to have a fallback page for URLs that do not match any defined routes. This provides a better user experience and helps handle potential errors more gracefully.
Q: Can I use React Router Dom with other state management libraries like Redux or MobX?
A: Yes, React Router Dom can be used in conjunction with other state management libraries. It provides a declarative way of handling routing, while libraries like Redux or MobX can manage the application's overall state.
Q: Can I use React Router Dom with TypeScript?
A: Yes, React Router Dom has TypeScript definitions available and can be used seamlessly with a TypeScript project. Make sure to install the required type declarations for TypeScript integration.
Q: Is there a limit to the number of routes I can define in a React app?
A: There is no strict limit to the number of routes you can define. However, keep in mind that as the number of routes increases, the complexity of managing and organizing them may also increase. Consider structuring your routes in a logical and maintainable way to avoid potential issues.