React Router
React Router is a standard and most popular library for routing in React. It is used to manage navigation and rendering different components as pages based on the URL.
React Router provides a set of components and functions, which makes it easy to create a dynamic single-page app in React.
If you want to understand it more detailed, Then:
As you do page routing in regular HTML, you have a index.html which is your Home page and contact.html which is your Contact page, then when you navigate from home page to contact page, the URL is something like this:
yourdomain.com/contact.html
And, the browser reloads every time when you navigate from one page to another page, that’s why it works very slow.
But when you use React, page navigation is super fast, because the browser does not reload every time when you navigate page to page. Also the URL looks like this:
yourdomain.com/contact
So let’s see How you can use React Router and implement the Routing feature in React.
Installation of React Router
To install react-router in your react app, write the following command and run this in your terminal.
npm install react-router-dom
Importing React Router
After installing the react-router-dom, import the necessary components from it.
Import these in the App.js file.
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
Components in React Router
As you can see in the above code example, I have imported Three components of React Router from react-router-dom.
Here the BrowserRouter component is the primary component of the React Router, It is used to set up routing in the react app.
Here I have imported the BrowserRouter as Router, like instead of writing BrowserRouter everywhere you can use the Router, it’s just the way to give it a shorter name. This will make your code more concise, behavior will be the same, only we give a name different to keep our code clean.
Apart from this, we have imported two more components from react-router-dom, that are Routes and Route.
Here the Routes component will contain all the routes, and the Route component will define different routes and associate them with specific components.
Routing Example – Static Routing
Step 1
Before going further, let’s create some components for your react app.
In the src folder create another folder named pages, then inside this, create Four new files:
1 – `Home.js` – as Home page/main index page.
2 – `About.js` – as About page.
3 – `Contact.js` – as Contact page.
4 – `NotFound.js` – as 404 not found page.
Folder structure will be something like this.
├── src/ │ ├── pages/ │ │ ├── Home.js │ │ ├── About.js │ │ ├── Contact.js │ │ └── NotFound.js
I have added h1 elements in each component for displaying the Title text.
Home.js
import React from 'react' function Home() { return ( <h1>Home - Welcome</h1> ) } export default Home;
About.js
import React from 'react' function About() { return ( <h1>About Page</h1> ) } export default About;
Contact.js
import React from 'react' function Contact() { return ( <h1>Contact Page</h1> ) } export default Contact;
NotFound.js
import React from 'react' function NotFound() { return ( <h1>404 - Not Found</h1> ) } export default NotFound;
Step 2
Then come to your `App.js` file. Here import all the components from the `src/pages` directory which you have made previously. Delete all the JSX elements we inserted earlier.
Then inside the div JSX element. Add the Router component, then inside the Router component, Routes component is used to define the different routes and their associated components.
Then Route components are used to define individual routes.
The `index` keyword is used to indicate the default route. Each Route has a `path` and an
`element` prop.
The `path` prop defines the URL path associated with the route.
The `element` prop specifies the component that should be rendered when the route is matched.
The last Route with `path=”*”` acts as a “catch-all” route, It will render the NotFound(404 page) component when any of these defined components would not match.
The final code is below:
//App.js import "./App.css"; import React, { useEffect, useState } from "react"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import About from "./pages/About"; import Contact from "./pages/Contact"; import NotFound from "./pages/NotFound"; function App() { return ( <div className="App"> <Router> <Routes> <Route index path="/" element={<Home/>} /> <Route path="/about" element={<About/>} /> <Route path="/contact" element={<Contact/>} /> <Route path="*" element={<NotFound/>} /> </Routes> </Router> </div> ); } export default App;
step 3
Then create a Header Component (Header.js) inside the `src/components` folder. Basically we will create a header navbar with navigation links.
import React from 'react' import { Link } from 'react-router-dom'; function Header() { return ( <header> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/contact">Contact</Link> </li> </ul> </nav> </header> ) } export default Header;
As you can see in the above code, I have imported the `Link` component from
react-router-dom, it allows you to create links to different routes in your React Web App without the `<a></a>` tag.
Then import this Header component in your root component (`App.js`) and render inside the `Router` component, so that this Header Component will display in every route. Code example given below:
function App() { return ( <div className="App"> <Router> //Header Component inside the Router component. <Header /> <Routes> <Route index path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> </div> ); }
Final code of your Root Component (`App.js`):
//App.js import "./App.css"; import React, { useEffect, useState } from "react"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import About from "./pages/About"; import Contact from "./pages/Contact"; import NotFound from "./pages/NotFound"; import Header from "./components/Header"; function App() { return ( <div className="App"> <Router> <Header /> <Routes> <Route index path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> </div> ); } export default App;
Output
This is the output of the Home route or Home page.
This is the output of the About route or About page. URL – http://localhost:3000/about
This is the output of the Contact route or Contact page. URL –
http://localhost:3000/contact
404 Error – Not Found page will show, when you try to access a URL that doesn’t correspond to any of the defined routes in your React application.
Dynamic Routing in React
Dynamic routing in React refers to the process of creating routes that can handle variable or dynamic parts in the URL. You can build more flexible and data-driven web apps using the dynamic routing feature in ReactJs, where different content is displayed based on the parameters in the URL.
Importance of Dynamic Routing than Static Routing
As we have learned earlier about the Static Routing Method in React.
Suppose, You are building an e-commerce web app, you have 100 products and you want to display each product’s details as a specific product page based on their unique URLs.
Like if you want to see the details of product no.1 then you would access the URL https://yourdomain/product/1
So, for this you would have to manually create 100 routes and components for each product page. Like this:
import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Product1 from "./pages/Product1"; import Product2 from "./pages/Product2"; import Product3 from "./pages/Product3"; import Product4 from "./pages/Product4"; //...up to Product100 function App() { return ( <div className="App"> <Router> <Routes> <Route path="/product/1" element={<Product1/>} /> <Route path="/product/2" element={<Product2/>} /> <Route path="/product/3" element={<Product3/>} /> <Route path="/product/4" element={<Product4/>} /> {/* ...more routes up to Product100 */} </Routes> </Router> </div> ); } export default App;
No doubt this method will work fine, but hard to maintain and it’s not an efficient approach to do like this.
So, that’s why React provides us with the Dynamic Routing feature. Let’s see how you can simplify this process using Dynamic Routing?
Building a Dynamic Routing structure
Using Dynamic Routing, you can create a single route for all products, then you can fetch the content dynamically based on the URL parameters.
Let’s build step by step:
Step 1:
First create a component inside the src/pages called Product.js, it will be our single component for all the products.
Then import this component in the Root Component (App.js), like this:
import Product from "./pages/Product";
Then create a new Route inside the Routes component in App.js, like this:
<Routes> {/* dynamic route for products */} <Route path="/product/:productId" element={<Product/>} /> </Routes>
In the above code example,
`path=”/product/:productId”`: This sets the URL pattern for the route. It uses a dynamic parameter `:productId` which indicates that the route can match URLs like `/product/35`, where 35 is the actual productId.
Step 2:
Edit your `Product.js` Component, like this:
import React from 'react' import { useParams } from 'react-router-dom'; function Product() { const { productId } = useParams(); return ( <div> <h1>Product {productId}</h1> <p>This is the product about {productId}.</p> </div> ) }; export default Product;
In the above code of `Product.js`, as you can see, I have imported the `useParams` hook from react-router-dom.
Then `const { productId } = useParams();`: This line uses the `useParams` hook to extract the productId parameter from the URL. Here the `useParams` hook returns an object containing all the URL parameters specified in the route.
In this case, we are destructuring the `productId` parameter from that object.
Then also I used that `productId`in the JSX elements.
Let’s see the output:
Output when you access the URL – /product/10
You can now get details of the product no.100 or 1000, by just adding the `productId`
parameter in the URL.
Additional Step:
This step will be the bonus for you.
So, come to the Home component (Home.js), here we will build some product cards to showcase all the products in the Home page and will add navigation links in every card.
So that when the user wants to know about the details of any specific product, then he will navigate to the page of that individual product by clicking on the link which will be in that specific product card.
import React from 'react' import { Link } from 'react-router-dom'; function Home() { const productNumbers = [1, 2, 3, 4, 5]; return ( <> <h1>Home - Welcome</h1> {/* Products card */} {productNumbers.map((item) => ( <div className="product_card" key={item}> <h2>Product {item}</h2> <Link to={`product/${item}`}>View</Link> </div> ))} </> ) } export default Home;
In the above code I have defined an array named productNumbers containing a list of product numbers as product ID which will be used as productId parameter.
Then I used the `map()` method to iterate over each item in the productNumbers array and create a set of product cards. Here Five cards will be rendered as the Array contains Five items.
I have taken an argument in the map() function called `item` as currentValue.
Then I have created navigation links using the Link component. It will be dynamically generated based on the `item` value. This will lead to URLs like /product/1, /product/2, and up to /product/5.
After adding some CSS and styling the cards, the output will be:
Now you can click on the view link, to navigate that specific product page.
Okay, I hope you have understood all the things about this topic.