React

라우팅 심화

pjh8838 2024. 7. 5. 10:48
반응형

 

 

 

import logo from './logo.svg';
import './App.css';
import {createBrowserRouter, RouterProvider, useParams} from 'react-router-dom';
import Home from './pages/Home';
import Products from './pages/Products';
import ProductsDetail from './pages/ProductsDetail';
import ProductsDetail2 from './pages/ProductsDetail2';
import RootLayout from './pages/RootLayout';
import ErrorPage from './pages/ErrorPage';
import Users from './components/Users';

const router = createBrowserRouter([
  {
    path:"/",
    element: <RootLayout />,
    errorElement:<ErrorPage />,
    children: [
      {
        path:"/",
        element:<Home />
      },
      {
        path:"/products",
        element:<Products />
      },
      {
        path:"/users",
        element:<Users />,
        loader: async function() {
          var url = "https://reqres.in/api/users?page=2";
          var response = await fetch(url);
          var json = await response.json();
          var userList = json.data;
          return userList;
        }
        //users 요청하면 Users 가기전에 loader 함수 실행
      }
    ]
  }
]);

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

export default App;

 

import { useLoaderData } from "react-router-dom";
import UserList from "./UserList";


function Users() {

    const xxx = useLoaderData();
    console.log(xxx);

    return(
        <>
            <h2>Users</h2>
            <UserList userList={xxx}/>
        </>
    );
}

export default Users;

 

import { useLoaderData } from "react-router-dom";


function UserList({ userList }) {

    const xxx = useLoaderData();
    console.log(xxx);

    return (
        <>
            <h2>UserList</h2>
            {
                userList.map((row, idx) =>
                    <tbody key={idx}>
                        <tr>
                            <td>{row.id}</td>
                            <td>{row.email}</td>
                            <td>{row.first_nanme}</td>
                            <td><img src={row.avatar}></img></td>
                        </tr>
                    </tbody>
                )
            }
        </>
    );
}

export default UserList;

 

728x90
반응형

'React' 카테고리의 다른 글

Tanstack Query 사용 전 기본적인 데이터 통신  (0) 2024.07.15
라우팅 심화2  (0) 2024.07.05
SpringBoot 실행실습  (0) 2024.07.04
라우팅  (0) 2024.07.04
추가하기 ( input으로 입력 받은 데이터 추가하기 )  (0) 2024.07.03