1. component import 및 export하기
2. 동일한 파일에서 여러 component import 및 export하기
1-1. component import 및 export하기
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
App.js
KeyNote
- 가끔 .js와 같은 파일 확장자가 없는 때도 있다.
import Gallery from './Gallery';
- React에서는
'./Gallery.js'
또는'./Gallery'
둘 다 사용할 수 있지만 전자의 경우가 ES Modules 사용 방법에 더 가깝다.
1-2. 동일한 파일에서 여러 component import 및 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를 Profile
로 named export 합니다.Gallery
component를 default export 합니다.App.js
Gallery.js
에서 Profile
를 Profile
로 named import 합니다.Gallery.js
에서 Gallery
를 default import 합니다.App
컴포넌트를 default export 합니다.