“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.
- 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!! 😊