[ 요약 ]
Root 컴포넌트
: 최상위 컴포넌트로, 하위 컴포넌트와 부모 관계을 가지며 트리 구조 형성default import(export)
: 한 파일에 한 개만 존재named import(export)
: 한 파일에 여러 개 존재 가능
[ 학습 내용 ]
- Root 컴포넌트란
- 컴포넌트를 import 하거나 export 하는 방법
- 언제 default 또는 named imports와 exports를 사용할지
- 한 파일에서 여러 컴포넌트를 import 하거나 export 하는 방법
- 여러 컴포넌트를 여러 파일로 분리하는 방법
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>
);
}
[ 컴포넌트를 다른 파일로 이동하는 단계 ]
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 export
라는 두 가지 방법으로 export
한 파일에서는 하나의 default export만 존재 가능
export default function Button() {}
import Banana from './button.js'
named export는 여러 개 존재 가능
export function Button() {}
import { Button } from './button.js';
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