CodeBlanks Logo Icon CodeBlanks

Meydan okuma: Rotalı sepet

React Router ile ürün listesi, detay ve sepet rotaları yazarsın.

Meydan okuma: Rotalı sepet

Bu meydan okumada React Router ile bir sepet uygulaması kuracaksın. / rotası ürün listesini, /cart/:id rotası tek bir ürünü göstersin.

useParams ile URL'den id al, products.find(p => p.id === id) ile ürünü bul. Rotaları <Routes> içinde tanımla.

Bu, e-ticaret sitelerinin temel iskeletidir.

Uygulama Rotalı sepet

ProductList bileşeni yaz: <ul> içinde ürünleri listeleyen <li>'ler bas. ProductPage bileşeni yaz: useParams() ile id al, products.find(p => p.id === Number(id)) ile ürünü bul, <h1>{product.name}</h1> bas. CartApp bileşeni yaz: <BrowserRouter> içinde <Routes> ile path="/" element <ProductList /> ve path="cart/:id" element <ProductPage />. export default CartApp.

Başlangıç kodu

App.jsx
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";

const products = [{ id: 1, name: "Kalem" }, { id: 2, name: "Defter" }];

// ProductList, ProductPage, CartApp bileşenlerini buraya yaz

Örnek çözüm

App.jsx
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";

const products = [{ id: 1, name: "Kalem" }, { id: 2, name: "Defter" }];

function ProductList() {
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}

function ProductPage() {
  const { id } = useParams();
  const product = products.find((p) => p.id === Number(id));
  return <h1>{product.name}</h1>;
}

function CartApp() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<ProductList />} />
        <Route path="cart/:id" element={<ProductPage />} />
      </Routes>
    </BrowserRouter>
  );
}

export default CartApp;

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 URL'den id parametresini almak için?

  • useParams Doğru cevap
  • useState
  • useNavigate
  • useLocation

Açıklama: useParams URL parametrelerini verir.

2 Route path

Soru
<Route path="____" element={<ProductPage />} />
Cevap
<Route path="cart/:id" element={<ProductPage />} />

Açıklama: :id bir URL parametresi tanımlar.

Orta seviye bölümündeki tüm dersler