[React] UI 표현하기 - 컴포넌트 import 및 export 하기

Gyuhan Park·2024년 1월 29일
0

공식문서

목록 보기
2/10

[ 요약 ]

  • Root 컴포넌트 : 최상위 컴포넌트로, 하위 컴포넌트와 부모 관계을 가지며 트리 구조 형성
  • default import(export) : 한 파일에 한 개만 존재
  • named import(export) : 한 파일에 여러 개 존재 가능

[ 학습 내용 ]

  • Root 컴포넌트란
  • 컴포넌트를 import 하거나 export 하는 방법
  • 언제 default 또는 named imports와 exports를 사용할지
  • 한 파일에서 여러 컴포넌트를 import 하거나 export 하는 방법
  • 여러 컴포넌트를 여러 파일로 분리하는 방법

📘 Root 컴포넌트란?

Profile과 Gallery 컴포넌트 모두 App.js 라는 root 컴포넌트 존재
root 컴포넌트에서 트리가 시작되어 하위 컴포넌트들이 트리 구조로 형성

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

📘 컴포넌트를 import 하거나 export 하는 방법

[ 컴포넌트를 다른 파일로 이동하는 단계 ]
1. 컴포넌트를 추가할 JS 파일 생성
2. 새로 만든 파일에서 함수 컴포넌트를 export (default 또는 named export)
3. 컴포넌트를 사용할 파일에서 import (적절한 방식을 선택해서 default 또는 named로 import)

🚨 중요합니다!

파일 확장자가 없는 경우 존재

import Gallery from './Gallery';

React에서는 './Gallery.js' 또는 './Gallery' 둘 다 사용할 수 있지만 전자의 경우가 native ES Modules

🚨 Default와 Named Exports

defaultnamed export 라는 두 가지 방법으로 export
한 파일에서는 하나의 default export만 존재 가능

export default function Button() {}	

import Banana from './button.js'

named export는 여러 개 존재 가능

export function Button() {}	

import { Button } from './button.js';

📘 한 파일에서 여러 컴포넌트를 import 하거나 export 하는 방법

named export 방식을 사용해서 Gallery.js 파일에서 Profile 컴포넌트를 export

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

named import 방식으로 Gallery.js 파일에서 Profile 컴포넌트를 App.js 파일로 import

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

https://ko.react.dev/learn/importing-and-exporting-components

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글