본문 바로가기

이것저것 스터디📚/React - 공식 문서

React 공식문서 - Importing and Exporting Components

컴포넌트의 가장 큰 장점은 재사용성으로 컴포넌트를 조합해 다른 컴포넌트를 만들 수 있다는 점이다. 컴포넌트를 여러 번 중첩하게 되면 다른 파일로 분리해야 하는 시점이 생기는데, 이렇게 분리하면 나중에 파일을 찾기 더 쉽고 재사용하기 편리해진다.

 

The root component file(루트 컴포넌트 파일)

 

CRA(Create React App)에서는 앱 전체가 src/App.js라는 root 컴포넌트에서 실행된다.(설정에 따라 root 컴포넌트가 다른 파일에 위치할 수도 있다.)

 

* Creact React App

CRA는 Create React App의 약어로, 초기 설정과 번들링 등의 작업을 자동화하여 React 애플리케이션을 쉽게 생성하기 위한 도구입니다. CRA를 사용하면 개발 환경 구성을 위한 복잡한 설정 과정을 거치지 않고, 명령어 한 줄로 기본적인 React 프로젝트 구조와 설정이 자동으로 생성되며, CRA는 Babel, Webpack, ESLint 등과 같은 도구들을 미리 설정하여 사용자가 추가 설정을 할 필요가 없도록 제공한다.


Exporting and importing a component(컴포넌트 import 및 export 하기)

 

모듈성을 강화시키고 다른 파일에서 재사용할 수 있게 기존 컴포넌트를 root 컴포넌트 밖으로 옮기는 방법.

 

1. 컴포넌트를 넣을 JS 파일을 생성한다.

2. 새로 만든 파일에서 함수 컴포넌트를 export 한다.(default 또는 named export 방식 사용)

3. 컴포넌트를 사용할 파일에서 import 한다.

// 기존의 App.js
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>
  );
}
// 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 />
  );
}

 

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

import Gallery from './Gallery';

 

* Default exports vs named exports

Syntax Export statement Import statement 특징
Default export default function Button() {} import Button from './Button.js'; 한 파일에서 하나만 존재
Named export function Button() {} 또는
function Button() {}
export { Button }
import { Button } from 'Button.js'; 한 파일에서 여러개 존재 가능

Exporting and importing multiple components from the same file(동일한 파일에서 여러 컴포넌트 import 및 export 하기)

 

앞선 예제에서 Profile 파일 또한 export를 하고 싶다면, 이미 export default가 사용되고 있기 때문에 named export 방식을 사용해야 한다.

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>
  );
}

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

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

* 참고 : React 공식문서(https://react-ko.dev/learn)