단순 코드 기록/React

React_동적 라우팅_useParams

일일일코_장민기 2024. 3. 21. 11:10
728x90

 

 

 

 

 

import { Link } from "react-router-dom"             //Link 추가

const ProductList = [
    { id: "p1", title: "Product 1"},
    { id: "p2", title: "Product 2"},
    { id: "p3", title: "Product 3"},
];

export default function Products(){

    return(
        <>
            <h1>The Products Page</h1>

            {/* App.js 수정 */}
            <ul>
                {ProductList.map((row, idx) => {
                    let link="/products/"+row.id;           //그냥 입력할 경우
                //  let link=`/products/${row.id}`;         //백틱을 사용할 경우
                    return(
                        <li key={idx}>
                            <Link to={`/products/${row.id}`}>{row.title}</Link>
                        </li>
                    )
                })}
            </ul>
        </>
    )
}

 

 

 

import HomePage from "./pages/Home"
import Products from "./pages/Products"
import RootLayout from "./pages/root";
import Error from "./pages/Error";
import ProductDetail from "./pages/ProductDetail"                 //ProductDetail 페이지 연결
import { createBrowserRouter, RouterProvider } from "react-router-dom"

const router = createBrowserRouter(              
  [{
    path: "/",
    element: <RootLayout/>,
    errorElement: <Error/>,                  
    children: [
      {path: "/", element: <HomePage/>},
      {path: "/products", element: <Products/>},
      {path: "/products/:productId", element: <ProductDetail/>},  //:productId를 useParams로 전송(${row.id})
    ]
  }]
);

export default function App(){

  return(
    <>
      <h1>App</h1>
      <RouterProvider router={router}></RouterProvider>
    </>
  )

}
import { Link, useParams } from "react-router-dom"

export default function ProductDetail(){

    const params = useParams();

    return(
        <>
            <h1>ProductDetail</h1>
            <p>{params.productId}</p>

            {/* relative = 'route' 하나의 경로 (Home으로 이동)*/}
            <Link to=".." relative="route">back1</Link><br></br>

            {/* relative = 'path' 두 개의 경로 (Products로 이동)*/}
            <Link to=".." relative="path">back2</Link><br></br>

            {/* relative = '' 하나의 경로 */}
            <Link to="..">back3</Link><br></br>
        </>
    )
}