[리액트 공식문서 읽기] DESCRIBING THE UI - Importing and Exporting Components

JaeHong Jeong·2023년 8월 7일
post-thumbnail

Overview

컴포넌트의 마법은 재사용성에 있다 : 컴포넌트를 다른 컴포넌트들로 구성하여 만들 수 있다. 하지만 많은 컴포넌트들을 중첩시킬 수록 각각 다른 파일로 분리시키는 게 좋다. 이러면 쉽게 파일을 스캔할 수 있고 더 많은 곳에서 컴포넌트를 재사용할 수 있다.

The root component file

첫번째 컴포넌트에서 Profil컴포넌트와 이를 렌더링하는 Gallery 컴포넌트를 만들었다.

function Profile() {
  return (
    <img
      src="https://i.imgur.com/MK3eW3As.jpg"
      alt="Katherine Johnson"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

현재 이 예제에서 App.js라고 하는 루트 컴포넌트 파일에 있다. Create React App에서 앱은 src/App.js에 있다. 하지만 설정에 따라, 루트 컴포넌트는 다른 파일에 있을 수 있다. Next.js와 같은 파일 기반 라우팅을 사용하는 프레임워크를 사용한다면 루트 컴포넌트는 페이지마다 다르다.

Exporting and importing a component

앞으로 랜딩화면을 바꾸고 거기에 과학책 리스트를 넣고 싶다면? 혹은 모든 프로필을 다른 곳에 배치한다면? 루트 컴포넌트에서 GalleryProfile을 옮기는 것이 좋다. 이건 더 모듈화하고 재사용성이 좋게 한다. 다음 세가지 스텝에 따라 컴포넌트를 이동시킬 수 있다. :

  1. 컴포넌트를 넣을 새로운 JS파일을 만든다.
  2. 파일에서 함수 컴포넌트를 Export 시킨다. ( default 혹은 named exports 방식을 사용한다.)
  3. 컴포넌트를 사용할 파일에 Import 시킨다. ( default 혹은 named exports 방식에 알맞는 importing 기술을 사용한다. )

ProfileGalleryApp.js에서 새로운 파일Gallery.js로 옮겼다. Gallery.js에서 Gallery를 가져오도록 App.js를 변경할 수 있다.

// Gallery.js

function Profile() {
  return (
    <img
      src="https://i.imgur.com/QIrZWGIs.jpg"
      alt="Alan L. Hart"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}
// App.js

import Gallery from './Gallery.js';

export default function App() {
  return (
    <Gallery />
  );
}

예제가 이제 어떻게 두 개의 구성 요소 파일로 나뉘는지 확인해라:

  1. Gallery.js:
    • 동일한 파일 내에서만 사용되고 내보내지지 않는 Profile을 정의
    • default exportGallery Exports 하기
  2. App.js:
    • default importGallery.js에서 Gallery Imports 하기
    • default export로 루트 컴포넌트 App Exports 하기
💡 Note

다음과 같이 .js 파일 확장자가 없는 파일이 나타날 수 있다.
import Gallery from './Gallery';
'./Gallery.js''./Gallery' 둘 다 리액트에서 작동하지만 전자는 기본 ES Modules 방식에 가깝다

Exporting and importing multiple components from the same file

갤러리 대신 Profile 하나를 보여주고 싶으면 어떡할까? Profile컴포넌트를 내보내면된다. 하지만 Gallery.js가 이미 default export 되어있고, 두개의 default export는 할 수 없다. default export 하기위해 새로운 파일을 만들거나, Profile 에 named export를 추가하는 방법도 있다. 파일에는 default export 하나만 있을 수 있지만 named exports는 여러 개 있을 수 있다.

💡 Note

default export와 named exports 사이에서 잠재적 혼란을 줄이기 위해 일부 팀들은 둘 중 하나만 선택하는 경우도 있다. 너에게 알맞은 방법을 선택해라

첫째, named export를 사용하여 Gallery.js에서 Profile을 내보내라

export function Profile() {
  // ...
}

그리고, 대괄호({})를 사용하여 App.js에서 Gallery.jsProfileimport 해라

import { Profile } from './Gallery.js';

마지막으로 App 컴포넌트에서 <Profile />을 렌더링해라

export default function App() {
  return <Profile />;
}

Gallery.js 에는 두개의 exports가 있다. : default export의 Gallery, named export의 Profile. App.js는 둘 다 import 한다. 이 예제에서 <Profile /><Gallery />로 편집하고 되돌려봐라.

// App.js

import Gallery from './Gallery.js';
import { Profile } from './Gallery.js';

export default function App() {
  return (
    <Profile />
  );
}
// Gallery.js

export function Profile() {
  return (
    <img
      src="https://i.imgur.com/QIrZWGIs.jpg"
      alt="Alan L. Hart"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

default export 와 named exports를 함께 사용하고 있다.

  • Gallery.js :
    • Profile 컴포넌트를 named export를 사용하여 **Profile**로 export한다.
    • Gallery 컴포넌트를 default export를 사용하여 export한다.
  • App.js
    • Gallery.js에서 **Profile**Profile 컴포넌트를 named import한다.
    • Gallerey.js에서 Gallery를 default import한다.
    • App을 default export한다.

Recap

이 장에서 공부한 것 :

  • 루트 컴포넌트가 무엇인지
  • 컴포넌트를 import, export하는 방법
  • 언제 default, named import, exports를 사용하는가
  • 같은 파일에서 여러개의 컴포넌트 export하는 방법
profile
반갑습니다.

0개의 댓글