xxxxxxxxxx
// Users.js file
import React from "react";
import { Link, Outlet} from "react-router-dom";
function Users() {
const users = [
{id: 1, name: 'User 1 details'},
{id: 2, name: 'User 2 details'},
{id: 3, name: 'User 3 details'},
]
return (
<div>
{users.map((item) => (
<Link to={`/users/${item.id}`} key={item.id}><h5>{item.name}</h5></Link>
))}
<Outlet />
</div>
);
}
export default Users;
xxxxxxxxxx
/* Links */
{heroes.map(hero => (<Link to={'heroes/' + hero.id} />)}
<Router>
/* Component */
<Route path="heroes/:id" component={Hero} />
</Router>
import { useParams } from "react-router-dom";
const Hero = () => {
const params = useParams();
// params.id => dynamic value defined as id in route
// e.g '/heroes/1234' -> params.id equals 1234
return ( )
}
dynamic routes with react-router-dom
xxxxxxxxxx
Update so this works for React Router v6:
React Router v6 brought some changes to the general syntax:
Before: <Route path="heroes/:id" component={Hero} />
Now: <Route path="heroes/:id" element={<Hero />} />
You can't access params like with this.props.match anymore:
Before: this.props.match.params.id
Now: import {useParams} from "react-router-dom";
const {id} = useParams();
You can now just use id as any other variable.