React 공식문서 이해하기 (2)

Syoee·2023년 11월 10일
0

React

목록 보기
2/30
post-thumbnail

Chapter 1. Describing the UI

#2 Component import 및 export

학습 목차

1. component import 및 export하기
2. 동일한 파일에서 여러 component import 및 export하기


1. Root Component 파일

1-1. component import 및 export하기

  • Component를 넣을 JS 파일을 생성한다.
  • 새로 만든 파일에서 함수 component를 export 한다.
    default 또는 named export 방식을 사용
  • Component를 사용할 파일에서 import 한다.
    default 또는 named export에 대응하는 방식으로 import 한다.

KeyNote

  • Create React App에서는 앱 전체가 src/App.js에서 실행된다.
    설정에 따라 Root 컴포넌트가 다른 파일에 위치할 수도 있다.
  • Next.js처럼 파일 기반으로 라우팅하는 프레임워크일 경우 페이지별로 root component가 다를 수 있다.

아래의 예시를 참고하자.

// App.js

import Gallery from './Gallery.js';

export default function App() {
  return (
    <Gallery />
  );
}
// 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>
  );
}
  • Gallery.js

    • 동일한 파일 내에서만 사용되며 export하지 않는 Profile component를 정의한다.
    • Gallery 컴포넌트를 default export 방식으로 export 한다.
  • App.js

    • Gallery를 Gallery.js로부터 default import 방식으로 import 한다.
    • root App 컴포넌트를 default export 방식으로 export 한다.

KeyNote

  • 가끔 .js와 같은 파일 확장자가 없는 때도 있다.
    import Gallery from './Gallery';
  • React에서는 './Gallery.js' 또는 './Gallery' 둘 다 사용할 수 있지만 전자의 경우가 ES Modules 사용 방법에 더 가깝다.

1-2. 동일한 파일에서 여러 component import 및 export하기

  • default export를 두 개 가질 수는 없다.
  • 한 파일은 default export를 하나만 가질 수 있지만, named export는 여러 개 가질 수 있다.

KeyNote

  • default export와 named export 사이의 잠재적인 혼동을 줄이기 위해 일부 팀에서는 한 가지 스타일(default 또는 named)만 고수하거나, 단일 파일 내에서 혼합하지 않도록 선택한다.
  • 자신에게 가장 적합한 방식을 선택하는 것을 권장한다.

아래의 예시를 참고하자.

// 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>
  );
}
  • Gallery.js

    • Profile component를 Profilenamed export 합니다.
    • Gallery component를 default export 합니다.
  • App.js

    • Gallery.js에서 ProfileProfilenamed import 합니다.
    • Gallery.js에서 Gallerydefault import 합니다.
    • root App 컴포넌트를 default export 합니다.

요약

  • Root component란?
  • 컴포넌트를 import 하거나 export 하는 방법
  • 언제, 어떻게 default 및 named import, default 및 named export를 사용하는지
    한 파일에서 여러 component를 export 하는 방법

React 공식 문서

https://react.dev/

React 비공식 번역 문서

https://react-ko.dev/

profile
함께 일하고 싶어지는 동료, 프론트엔드 개발자입니다.

0개의 댓글

관련 채용 정보