Let's say I want to fetch data from an API but I also want to link each individual piece of data to its own individual page.
import React, { useState, useEffect } from "react";
This component is going to grab API data to display in the shop.
function Shop() {
// USE EFFECT //
useEffect(() => {
fetchItems();
}, []);
// STATE SETUP //
const [items, setItems] = useState([]);
// FETCH FROM API //
const fetchItems = async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/users");
const items = await data.json();
console.log(items);
setItems(items);
};
// RETURN DATA //
return (
<div>
{items.map(item => (
<h1 key={item.id}>
<Link to={`/shop/${item.id}`}>{item.name}</Link>
</h1>
))}
</div>
items
array and returning each item as an <h1>
link which will link to the specific item id./shop/${item.id}
<Link to={`/shop/${item.id}`}>
{item.name}
</Link>
So, now we need actually add that path to the Router.
i.e.
<Route path="/shop/:id" component={ItemDetail} />
:id
will take this path to the individual item. This component will render when an individual item is clicked.
function Item({match}) {
// USE EFFECT //
useEffect(() => {
fetchItem();
console.log(match)
}, []);
// SET THE STATE //
const [item, setItem] = useState({
});
// FETCH INDIVIDUAL ITEM
const fetchItem = async () => {
const fetchItem = await fetch(`https://jsonplaceholder.typicode.com/users/${match.params.id}`);
const item = await fetchItem.json();
setItem(item);
console.log(item);
};
// RETURN STATEMENT //
return (
<div>
<h1>{item.name}</h1>
<h3>{item.username} | {item.email} </h3>
<a href>{item.website}</a>
</div>
Item
takes in match
${match.params.id}
which will give us that specific ID.React Router gist:
https://gist.github.com/jasheloper/3441e182e972de5d43b77496f5f380d8
You may not want to Render ALL the data onto the original component, you may want to split that data up.
Let's say you have an API that contains for example:
- Users
You may not want to display EVERYTHING. You may want to maybe list maybe a little info about that user but someone must click to see more data about that user.
Dynamic Routing allows you to link to a specific piece of data (i.e. ID) which then can render out even more data about piece.
It's kind of like when you go to a real website shop and you see a list of items. Realistically, you don't see everything about that item. You usually see maybe a photo, a price, and a description.
Dynamic Routing helps keep your pages clean and organized by:
<Link to={
/shop/${item.id}}>{item.name}</Link>
<Route path="/shop/:id" component={ItemDetail} />
Repo:
https://github.com/jasheloper/dynamic-routing