Front-end/React

React) Outlet, useOutletContext 기본 사용 방법 ... react-router-dom

오열매 2023. 2. 24. 21:24

1. Outlet

 

Outlet은 정의한 Router에서 특정 path에 해당하는 경로에 children이 있을 때, 해당 컴포넌트를 렌더링하도록 해주는 컴포넌트이다. 

 

반드시 부모 컴포넌트 내에서 정의해줘야 한다. 그래야 해당 컴포넌트의 자식 컴포넌트와 연결이 가능하기 때문이다.

 

 

 

* Router.tsx (일부)

 

      {
        path: "/users/:userId",
        element: <User />,
        children: [
          {
            path: "followers",
            element: <Followers />,
          },
        ],
      },

# 앞에 "/" 를 붙이면 절대경로(맨 처음부터 시작), 붙이지 않으면 부모 path에서부터 시작하는 상대경로이다.


 

* User.tsx (일부 ... Followers 컴포넌트의 부모 컴포넌트)

 

      <hr />
      <Link to='followers'>See Followers!</Link>
      <Outlet />
    </>

Link 컴포넌트를 통해 '부모경로/foloowers' 로 이동한다.

 

Outlet을 이 위치에 선언해줘야 한다. 부모 컴포넌트에 선언해야 Outlet 컴포넌트 자리에 자식 컴포넌트를 할당한다.

 

 


2. useOutletContext

 

useOutletContext는 Outlet 컴포넌트를 통해 자식 컴포넌트들에게 정보를 보내는 목적으로 쓰인다.

 

 

* User.tsx (일부)

 

      <Link to='followers'>See Followers!</Link>
      <Outlet context={{ nameOfMyUser: users[Number(userId) - 1].name }} />
    </>

Outlet 컴포넌트에 context 로 props를 보낸다. (객체 형태)

 

 

* Followers.tsx (일부)

 

interface IFollowersContext {
  nameOfMyUser: string;
}

export default function Followers() {
  const { nameOfMyUser } = useOutletContext<IFollowersContext>();
  return <h3>{`Here is ${nameOfMyUser}'s Followers!`}</h3>;
}

useOutletContext Hooks를 사용하여 Outlet 컴포넌트로 보낸 context 값을 받는다.

 

(context로 보낸 값의 타입을 지정해준다. ... ts)


참고)

 

- https://nomadcoders.co/react-masterclass/lectures/4050

- https://reactrouter.com/en/main/components/outlet

- https://nomadcoders.co/react-masterclass/lectures/4047