React 컴포넌트는 마크업(HTML)으로 뿌릴 수 있는 JavaScript 함수이다
- 리액트 컴포넌트 : UI를 만드는 코드 덩어리 (JS함수로 작성되고, 그 함수 안에서 HTML을 만들어주는 코드를 작성함)
export default function MyButton() {
return (
<div>
<button>클릭하세요</button>
<img
src="https://i.imgur.com/MK3eW3Am.jpg"
alt="Katherine Johnson"
/>
</div>
);
}
MyButton 함수 : 리액트 컴포넌트 -> <button>클릭하세요</button>라는 마크업 반환 컴포넌트 빌드 방법
1. 컴포넌트 내보내기 (export default 접두사)
2. 함수 정의하기
3. 마크업 추가하기
컴포넌트 중첩 및 구성
주의
export default function Gallery() {
// 🔴 절대 컴포넌트 안에 다른 컴포넌트를 정의하면 안 됩니다!
function Profile() {
// ...
}
// ...
}
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>
);
}
import Gallery from './Gallery.js'; // Default 방식
import { Profile } from './Gallery.js'; // Named 방식
export default function App() {
return (
<Profile />
);
}
named export 방식으로 Gallery.js 파일에서 Profile 컴포넌트 exportnamed import 방식으로 Gallery.js 파일에서 Profile 컴포넌트를 import (중괄호 사용)