Set of items:
// itemList.js
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
Using items array to make a set of links:
// ItemList.js
import React from 'react';
import { Link } from 'react-router-dom';
import { items } from './itemList';
function ItemList() {
return (
<div>
{items.map((item) => (
<li key={item.id}>
<Link to={`/item/${item.id}`}>{item.name}</Link>
</li>
))}
</div>
);
}
A Route using Route Params (itemId):
<Route path="/items/:itemId" element={<ItemDetail />} />
Route parameters are variables which refer to a string in URLs. These variables can be filled in with anything. In this case :itemId, a string which can be accessed.
import React from 'react';
import { useParams } from 'react-router-dom';
import { items } from './itemList';
export default function ItemDetail() {
const { itemId } = useParams();
const item = items.find((item) => item.id === parseInt(itemId));
if (!item) {
return <div>Item not found</div>;
}
return (
<div>
<h2>Item Detail</h2>
<p>ID: {item.id}</p>
<p>Name: {item.name}</p>
</div>
);
}
To access any route param, use the hook useParams. Returns an object with the variable names as properties, and arguments as the values.