ReactJS - Router
ReactJS - Router
Section titled “ReactJS - Router”Modern web applications often require navigation between different views or pages. In React, this is typically handled by a routing library. This chapter will guide you on setting up client-side routing in your React application using React Router, the most popular routing library for React.
We’ll be using React Router v6, which offers a modern, hook-based API. If you’ve used older versions, you’ll notice some differences, but the core concepts remain intuitive.
Step 1 - Install React Router DOM
Section titled “Step 1 - Install React Router DOM”To get started, you need to install the react-router-dom package. Open your terminal or command prompt, navigate to your project directory, and run:
your-project-directory> npm install react-router-domOr if you are using Yarn:
your-project-directory> yarn add react-router-domStep 2 - Create Components
Section titled “Step 2 - Create Components”Let’s create a few simple components for our routing example. We’ll have a main App component that serves as the layout (including navigation links) and three page components: Home, About, and Contact.
For this example, we’ll define them in App.js and main.js (or your application’s entry point). In larger applications, you’d typically place each component in its own file (e.g., components/Home.js).
src/App.js (Layout Component)
Section titled “src/App.js (Layout Component)”import React from 'react';import { Link, Outlet } from 'react-router-dom';
function App() { return ( <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> <hr /> {/* The Outlet component renders the matched child route's element */} <Outlet /> </div> );}
export default App;src/pages/Home.js (Page Component)
Section titled “src/pages/Home.js (Page Component)”import React from 'react';
function Home() { return <h1>Home Page</h1>;}
export default Home;src/pages/About.js (Page Component)
Section titled “src/pages/About.js (Page Component)”import React from 'react';
function About() { return <h1>About Page</h1>;}
export default About;src/pages/Contact.js (Page Component)
Section titled “src/pages/Contact.js (Page Component)”import React from 'react';
function Contact() { return <h1>Contact Page</h1>;}
export default Contact;Key changes and concepts introduced here:
-
Link: Used instead of<a>tags for navigating between routes without a full page reload. It updates the URL and allows React Router to render the appropriate component. -
Outlet: A component fromreact-router-domthat acts as a placeholder in the parent route’s element (here,App) to render the matched child route component.
Step 3 - Configure Routes
Section titled “Step 3 - Configure Routes”Now, let’s set up the routing configuration. This is typically done in your main application file (e.g., src/main.js or src/index.js). We’ll use BrowserRouter to enable HTML5 history API-based routing and Routes to define our route mappings.
src/main.js (or src/index.js)
Section titled “src/main.js (or src/index.js)”import React from 'react';import ReactDOM from 'react-dom/client';import { BrowserRouter, Routes, Route } from 'react-router-dom';import App from './App';import Home from './pages/Home';import About from './pages/About';import Contact from './pages/Contact';
const root = ReactDOM.createRoot(document.getElementById('root'));root.render( <React.StrictMode> <BrowserRouter> <Routes> <Route path="/" element={<App />}> {/* Index route for the parent path "/" */} <Route index element={<Home />} /> <Route path="about" element={<About />} /> <Route path="contact" element={<Contact />} /> </Route> </Routes> </BrowserRouter> </React.StrictMode>);Explanation of the routing setup:
-
BrowserRouter: Wraps your entire application (or the part that needs routing) to enable client-side routing. It uses the browser’s History API to keep your UI in sync with the URL. -
Routes: A container for multipleRoutecomponents. It intelligently picks the bestRouteto render based on the current URL. -
Route: Defines a mapping between a URL path and a React component.- The
pathprop specifies the URL segment. - The
elementprop takes a React element (e.g.,<YourComponent />) to render when the path matches. - Nested Routes: Notice how the
Home,About, andContactroutes are nested within theApproute. This meansAppacts as a layout component, and theOutletwithinAppwill renderHome,About, orContactbased on the path. indexRoute:<Route index element={<Home />} />specifies the default component to render when the parent route’s path (/in this case) is matched exactly. It’s like a default child route.
- The
When you run your application, you’ll see the navigation links. Clicking them will change the URL and render the corresponding page component within the App layout, without a full page refresh.
This setup demonstrates a common pattern: a main application shell (App) with navigation, and content areas (Outlet) that display different page components based on the route.
Further Learning:
React Router offers many more features like URL parameters, nested routes, programmatic navigation, and route protection. For more in-depth information, check the official React Router documentation: https://reactrouter.com/