728x90
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"
import ProductDetail2 from "./pages/ProductDetail2"
import Users, {loader as usersLoader} from "./pages/Users" //Alias
import { createBrowserRouter, RouterProvider } from "react-router-dom"
import axios from "axios";
const router = createBrowserRouter(
[{
path: "/",
element: <RootLayout/>,
errorElement: <Error/>,
id: "root",
loader: async function(){
console.log("loader root 사용");
const resData = await response.json();
return resData.data;
},
children: [
{path: "/", element: <HomePage/>},
{path: "/products", element: <Products/>},
{path: "/products/:productId", element: <ProductDetail/>},
{path: "/products2/", element: <ProductDetail2/>},
{path: "/users/", element: <Users/>, loader: usersLoader
//async function(){
// console.log("loader 사용");
// const response = await fetch("https://reqres.in/api/users?page=2");
// const resData = await response.json();
// return resData.data;
// },
},
]
}]
);
export default function App(){
return(
<>
<h1>App</h1>
<RouterProvider router={router}></RouterProvider>
</>
)
}
import UserList from "../components/UserList";
export default function Users(){
return(
<>
<h2>Users</h2>
<UserList></UserList>
</>
)
}
export async function loader(){
console.log("Users.loader 사용");
const resData = await response.json();
return resData.data;
}
import { useLoaderData, useRouteLoaderData } from "react-router-dom";
export default function UserList() { //수정
const events = useLoaderData();
//const events = useRouteLoaderData로("root"); //아이디를 지정하는 useRouteLoaderData로 변경
return (
<>
<h3>UserList</h3>
<table border={1}>
<tr>
<th>아이디</th>
<th>이메일</th>
<th>성</th>
<th>이름</th>
<th>이미지</th>
</tr>
{events.map((row, idx) => (
<tr key={idx}>
<td>{row.id}</td>
<td>{row.email}</td>
<td>{row.first_name}</td>
<td>{row.last_name}</td>
<td>
<img src={row.avatar} alt={`User ${row.id} avatar`}></img>
</td>
</tr>
))}
</table>
</>
);
}
'단순 코드 기록 > React' 카테고리의 다른 글
React_Error별 메세지 출력 (0) | 2024.03.21 |
---|---|
React_MainNavigation 로딩창 (0) | 2024.03.21 |
React_loader를 이용한 데이터 fetching (0) | 2024.03.21 |
React_useParams와 useSearchParams를 활용한 PathVariable/QueryString (0) | 2024.03.21 |
React_동적 라우팅_useParams (0) | 2024.03.21 |