Dynamic Routing in React JS

“When we say Dynamic routing, we mean routing that takes place as the page is rendered”. This means we have to define one single route that works for every item. This is known as Dynamic routing. Let’s make it clear with an example.

Let’s assume we have a list of items and we want to render a component of an individual item to show its details. So now, shall we create an individual route for each item?

The answer is No. Please see the below snippet:

<Routes>
<Route path="/" element={<Home />} />
<Route path="/items" element={<Items />} />
<Route path="/items/:id" element={<ItemDetails />} />
</Routes>

The last route is an example of a dynamic route. We will define it by simply adding a colon in front of the dynamic part of your route.

How can we get the dynamic value of the parameter (id in our case) and how to use it?

In class component

import React from 'react'
import Select from '@material-ui/core/Select';
class Items extends Component {
getItem = () => {
const id = event.target.value;
this.props.history.push(`/items/${id}`);
};
renderItem = (items) =>
items.map((item) => {
const { id, name } = item;
return <MenuItem value={id}>{name}</MenuItem>;
});
render() {
return (
<Select value={teamId} onChange={this.getItem}>
{this.renderItem(items)}
</Select>
);
}
}

In the above code, we have used this.props.history.push(`/items/${id}`) which will move the current page to the matching route.

class ItemDetails extends Component{
render(){
const {id} = this.props.match.params
return (
<div>Item id: {id}</div>
)
}
}

Now on the /item/${id} page, we will extract the id like above and use it.

In Functional component

We can carry out the same things that are mentioned above with React-Router hooks.

  1. useNavigate()
import { useNavigate } from "react-router-dom";
const Items = () => {
const navigate = useNavigate();
const getItem = () => {
const id = event.target.value;
navigate(`/items/${id}`);
};
const renderItem = ()=>items.map((item) => {
const { id, name } = item;
return <MenuItem value={id}>{name}</MenuItem>;
})
return (
<Select value={teamId} onChange={getItem}>
{renderItem()}
</Select>
);
};

2. useHistory()

import { useNavigate } from "react-router-dom";
const Items = () => {
const {push}= useHistory();
const getItem = () => {
const id = event.target.value;
push(`/items/${id}`);
};
const renderItem = ()=>items.map((item) => {
const { id, name } = item;
return <MenuItem value={id}>{name}</MenuItem>;
})
return (
<Select value={teamId} onChange={getItem}>
{renderItem()}
</Select>
);
};

In the below snippet, we are using useParams of react-router-dom to get the required params (id in below case).

import React from 'react';
import { useParams, useHistory } from 'react-router-dom';
const ItemDetails = () => {
const { id } = useParams();
return (
<div>Item Id: { id }</div>
);
}
export default ItemDetails;

Thanks for reading. Please share your views on this.

Happy Coding!! 😊

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

Importance of Test Scalar Tool

TestScalar is quick to access, convenient to execute, easy to track. Our popular web-based test planning software lets you focus on what matters: meeting...

From Requirements to Reporting: How to Use a Test Case Management Tool to Ace Your Software Testing

The Software Testing Life Cycle (STLC) is a process that describes the stages of testing software. It includes planning, design, execution, and reporting of...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million people die every year because of vehicle accidents . Vehicle safety features started with passive safety...

LEAVE A REPLY

Please enter your comment!
Please enter your name here