Introduction
In this chapter, we will explore React Router, a powerful library for handling routing in React applications. React Router allows you to create single-page applications with navigation and dynamic content. We will use the latest version of React Router to demonstrate how to set up routing in a simple website.
Table of Contents
- Setting Up a New React Project
- Installing React Router
- Basic Configuration
- Creating Routes
- Example: Home, About, and Contact Pages
- Using Links for Navigation
- Example: Navigation Menu
- Nested Routes
- Example: Nested Route for Services
- Redirects and Not Found Pages
- Example: 404 Page and Redirects
- Conclusion
Setting Up a New React Project
First, let’s create a new React project using the create-react-app tool.
- Open your terminal and run the following command:
npx create-react-app react-router-example - Navigate to the project directory:
cd react-router-example
Installing React Router
Next, let’s install React Router. Open your terminal and run the following command inside your project directory:
npm install react-router-dom
Basic Configuration
package.json
After installing React Router, your package.json should look something like this (relevant sections shown):
{
"name": "react-router-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.0.0",
"react-scripts": "5.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
// other configurations...
}
Basic Configuration
- Create a New File for Routes: In the
srcdirectory, create a new file namedAppRouter.js. - Define the Routes: Add the following code to
AppRouter.jsto set up basic routing:// src/AppRouter.js import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Contact from './Contact'; import NotFound from './NotFound'; function AppRouter() { return ( <Router> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> ); } export default AppRouter;Explanation:
BrowserRouteris used to wrap the application and enable routing.Routesis used to define the route configuration.Routeis used to define paths and their corresponding components.NotFoundcomponent is rendered for any undefined routes.
- Create the Page Components: Create
Home.js,About.js,Contact.js, andNotFound.jsin thesrcdirectory with the following content:// src/Home.js import React from 'react'; function Home() { return <h2>Home Page</h2>; } export default Home; // src/About.js import React from 'react'; function About() { return <h2>About Page</h2>; } export default About; // src/Contact.js import React from 'react'; function Contact() { return <h2>Contact Page</h2>; } export default Contact; // src/NotFound.js import React from 'react'; function NotFound() { return <h2>404 - Page Not Found</h2>; } export default NotFound; - Use the Router in
App.js: Opensrc/App.jsand modify theAppcomponent to use theAppRoutercomponent:// src/App.js import React from 'react'; import AppRouter from './AppRouter'; function App() { return ( <div> <AppRouter /> </div> ); } export default App; - Save and View Changes: Save the files and start your React application by running:
npm startOpen your browser and navigate to
http://localhost:3000. You should see the home page. You can navigate to/aboutand/contactto see the respective pages.
Using Links for Navigation
To enable navigation between pages, we use the Link component from react-router-dom.
Example: Navigation Menu
- Create a Navigation Component: In the
srcdirectory, create a new file namedNav.js. - Define the Navigation Component: Add the following code to
Nav.js:// src/Nav.js import React from 'react'; import { Link } from 'react-router-dom'; function Nav() { return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/contact">Contact</Link> </li> </ul> </nav> ); } export default Nav; - Include the Navigation in
AppRouter: Opensrc/AppRouter.jsand include theNavcomponent:// src/AppRouter.js import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Contact from './Contact'; import NotFound from './NotFound'; import Nav from './Nav'; function AppRouter() { return ( <Router> <Nav /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> ); } export default AppRouter; - Save and View Changes: Save the files and start your React application by running:
npm startYou should now see a navigation menu that allows you to navigate between the Home, About, and Contact pages.
Nested Routes
Example: Nested Route for Services
- Create a Services Component: In the
srcdirectory, create a new file namedServices.js. - Define the Services Component: Add the following code to
Services.js:// src/Services.js import React from 'react'; import { Route, Routes, Link } from 'react-router-dom'; function Services() { return ( <div> <h2>Services</h2> <ul> <li> <Link to="web-development">Web Development</Link> </li> <li> <Link to="app-development">App Development</Link> </li> </ul> <Routes> <Route path="web-development" element={<WebDevelopment />} /> <Route path="app-development" element={<AppDevelopment />} /> </Routes> </div> ); } function WebDevelopment() { return <h3>Web Development Service</h3>; } function AppDevelopment() { return <h3>App Development Service</h3>; } export default Services; - Add the Services Route: Open
src/AppRouter.jsand add theServicesroute:// src/AppRouter.js import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Contact from './Contact'; import NotFound from './NotFound'; import Services from './Services'; import Nav from './Nav'; function AppRouter() { return ( <Router> <Nav /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="/services/*" element={<Services />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> ); } export default AppRouter; - Update the Navigation Component: Open
src/Nav.jsand add a link to the Services page:// src/Nav.js import React from 'react'; import { Link } from 'react-router-dom'; function Nav() { return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/contact">Contact</Link> </li> <li> <Link to="/services">Services</Link> </li> </ul> </nav> ); } export default Nav; - Save and View Changes: Save the files and start your React application by running:
npm startYou should now see a nested route structure under the Services page, allowing you to navigate between Web Development and App Development services.
Redirects and Not Found Pages
Example: 404 Page and Redirects
- Update
NotFound.js: Ensure yourNotFound.jsdisplays a user-friendly message.// src/NotFound.js import React from 'react'; import { Link } from 'react-router-dom'; function NotFound() { return ( <div> <h2>404 - Page Not Found</h2> <p> Go back to <Link to="/">Home</Link> </p> </div> ); } export default NotFound; - Update
AppRouter.js: Ensure you have a wildcard route (*) to handle undefined routes.// src/AppRouter.js import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Contact from './Contact'; import NotFound from './NotFound'; import Services from './Services'; import Nav from './Nav'; function AppRouter() { return ( <Router> <Nav /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="/services/*" element={<Services />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> ); } export default AppRouter; - Save and View Changes: Save the files and start your React application by running:
npm startNow, navigating to any undefined route should display the 404 – Page Not Found message with a link to go back to the Home page.
Conclusion
In this chapter, we set up a new React project and configured React Router to handle navigation. We covered creating basic routes, using links for navigation, handling nested routes, and implementing redirects and not found pages. React Router provides a powerful and flexible way to manage navigation and routing in your React applications, enabling you to build dynamic and user-friendly single-page applications.