Dynamic Routing Made Easy: A React-Router-Dom Tutorial

MentorAide
5 min readJun 14, 2024

--

Let’s learn how we can get the data from the routes using the Dynamic Routing.

What is Dynamic Routing?

Dynamic routing in React refers to the practice of creating routes in a React application based on data or conditions rather than defining static routes.

Let’s try to understand Dynamic Routing using the word itself i.e. Dynamic and routing, Dynamic means “the capability to change” and Routing means “the process of redirecting a user to different pages based on their request”.

Simply put, the route we are defining in our App.js file can be changed by dynamically adding data to it. That means they are not fixed we can change them by applying some conditions.

Let’s understand by using some example

http://localhost:8000/user_1

This is a simple route path that we have created in our app.js file under the Router. This is fixed we cannot change the path, it will show you the component that it is programmed to, which will be the user component displaying user_1 data.

But the issue arises when we need to see different user details, we cannot create like 1000 routes for each of the users that is insane right I hope you agree with me. For that sole purpose, we use Dynamic Routing.

So in Dynamic Routing, the routes look like this

http://localhost:800/user/:id

I know there are a lot of changes from the above path so let’s see what are these changes and understand them all. First of all the biggest change is the :id , this code makes this path dynamic, we can add what we want by just replacing it. I mean it will replace it by itself you just have to add some data instead of the :id .

Let me show you how to add data http://localhost:800/user/user_1 you can notice right, we can make it user_2 or user_3 or user_4 whatever user data we want by just defining this one route path in our App.js file this is the Beauty of the Dynamic Routing.

It has solved a very huge problem for us. In both ways that will be in the Routes and also in the component as we don’t want to create multiple routes and we don’t need to create separate components for each and every user. We can pass and also we can access the dynamic data that we have added to our route path i.e. user_1 in our component and display the details accordingly.

Benefits of Dynamic Routing ?

  1. Scalability
    — Dynamic routing allows you to add new routes or modify existing routes without the need to manually update your route configuration.
  2. Code Splitting
    — Dynamic routing can be used in conjunction with code splitting to load only the necessary JavaScript bundles for a particular route.
  3. Nested Routes
    — With dynamic routing, you can easily define nested routes, allowing you to create complex page layouts and hierarchies.
  4. Data-Driven Routes
    — Dynamic routing allows you to fetch route data from an API or other data sources.
  5. Customization
    — Dynamic routing enables you to customize routes based on user roles or permissions.
  6. Route Parameters
    — You can define dynamic route parameters that change based on the URL, which can be helpful for creating dynamic and data-driven pages.
  7. Reduced Boilerplate
    — Dynamic routing can lead to reduced code duplication and boilerplate code.
    — Instead of defining each route manually, you can generate routes based on a data structure, reducing the potential for errors.

There we will add a dynamic route to get the user details according to the user_id we have passed using some conditions like button click or something else, this will render the user Component that is in the UserDetails.jsx file. In this file we will get the user_id from the routes, and using that we will display the user data on the screen.

//app.jsx
import "./App.css";
// Importing the React Router Dom
import {
BrowserRouter as Router,
Routes,
Route,
NavLink,
} from "react-router-dom";
import Home from "./Components/Home";
import About from "./Components/About";
import Contact from "./Components/Contact";
import Error from "./Components/Error";
import Profile from "./Components/Profile";
import Friends from "./Components/Friends";
import Request from "./Components/Request";
import Stranger from "./Components/Stranger";
import ContactSearch from "./Components/ContactSearch";
import User from "./Components/User";
import UserDetails from "./Components/UserDetails";
function App() {
const navigationActive = ({ isActive }) => {
return {
color: isActive ? "white" : "black",
textDecoration: "none",
};
};
return (
<Router>
{/* Creating the Navigation Link to go from one route to another using the NavLink */}
<nav>
<NavLink style={navigationActive} to="home">
Home
</NavLink>
<NavLink style={navigationActive} to="about">
About
</NavLink>
<NavLink style={navigationActive} to="contact">
Contact
</NavLink>
<NavLink style={navigationActive} to="users">
User
</NavLink>
</nav>
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} /> // This is the part where we are using dynamic Routing
<Route path="/users" element={<User />} />
// Dynamic Routing applied for getting different users detail
// By adding id when we call this path
<Route path="/users/:id" element={<UserDetails />} /> // This is the Nested Routing example
<Route path="/contact" element={<Contact />}>
<Route path="friends" element={<Friends />} />
<Route path="request" element={<Request />} />
<Route path="stranger" element={<Stranger />} />
<Route path="search" element={<ContactSearch />} />
</Route>
<Route path="/profile/:username" element={<Profile />} />
<Route path="*" element={<Error />} />
</Routes>
</Router>
);
}export default App;

In the above code, there are a lot of things but you need to focus on the user route and the user/:id they both are important. The user is the route from which we can access or go to the UserDeatils page by clicking a button. There we will use a button and when we click on it will navigate us to that user's detail page using the useNavigate hook from the react-router-dom.

// User.jsx
import React from 'react'
import { useNavigate } from 'react-router-dom'
const User = () => {
const navigate = useNavigate()
const users = ["user_1","user_2","user_3"]
return (
<section>
<div style={{fontSize:32, textAlign:"center", padding:10}} >Users</div>
{users.map((user,idx)=>{
return <button key={idx} onClick={() => navigate(`${user}`)}>{user}</button>;
})}

</section>
)
}export default User

Here in the code above, as you can see we have used an array, for our example to store the user details. And then we are mapping through the array and creating buttons for each and every user separately. We are adding an event to the button that is the onClick() event and as soon as the user clicks this button the event will be triggered and it will navigate the user to the specific user_details page using the useNavigate hook provided by the react-router-library.

Now the part comes where the UserDetails page will get the data and will show the user's details according to the button we clicked.

//UserDetails.jsx
import React from 'react'
import { useParams } from 'react-router-dom'
const UserDetails = () => {
const {id}= useParams()
console.log("Users details",id)
return (
<div style={{ fontSize: 32, textAlign: "center", padding: 10 }}>
UserId - {id}
</div>
);
}export default UserDetails

In the above code, we are using the useParam provided by the react-router-dom for getting the data. This is the final part where we can get the data from the URL or the path. The useParam when called provides us with an object that contains the name and the data in it. The name is the name we specified in the app.jsx file in our case it will be id. You can use any name you want and one more thing you can use multiple dynamic variables in a single path but carefully as it can lead to confusion.

--

--

MentorAide
MentorAide

No responses yet