← 돌아가기

Step 2: 컴포넌트 기초

😢 문제: 카드가 반복됨

반복되는 HTML

<div className="bg-white p-6 rounded-lg shadow">
  <h3 className="text-xl font-bold mb-2">프로필</h3>
  <p className="text-gray-600">홍길동</p>
</div>

<div className="bg-white p-6 rounded-lg shadow">
  <h3 className="text-xl font-bold mb-2">나이</h3>
  <p className="text-gray-600">25세</p>
</div>

<div className="bg-white p-6 rounded-lg shadow">
  <h3 className="text-xl font-bold mb-2">직업</h3>
  <p className="text-gray-600">개발자</p>
</div>

문제점

코드가 너무 길어요

똑같은 구조를 3번 반복

수정이 어려워요

스타일 변경시 3곳 모두 수정

실수하기 쉬워요

복사-붙여넣기로 오타 발생

✅ 해결: Card 컴포넌트 만들기

1️⃣ 컴포넌트 만들기

반복되는 부분을 함수로 만들고, 다른 부분은 props로 받습니다.

// components/Card.jsx
export default function Card({ title, content }) {
  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <h3 className="text-xl font-bold mb-2">{title}</h3>
      <p className="text-gray-600">{content}</p>
    </div>
  );
}

2️⃣ 컴포넌트 사용하기

이제 3줄이면 끝!

// app/page.jsx
import Card from "@/components/Card";

export default function Page() {
  return (
    <div className="flex flex-col gap-4 p-8">
      <Card title="프로필" content="홍길동" />
      <Card title="나이" content="25세" />
      <Card title="직업" content="개발자" />
    </div>
  );
}

실행 결과:

프로필

홍길동

나이

25세

직업

개발자

🎯 Props 이해하기

Props는 새로운 개념이 아닙니다! HTML의 attributes와 똑같습니다.

HTML 일반 태그

<img 
  src="photo.jpg" 
  alt="사진" 
/>

<a 
  href="https://google.com"
  target="_blank"
>
  구글
</a>

src, alt, href = attributes

이미 익숙하게 써왔던 것!

컴포넌트 (직접 만든 태그)

<Card 
  title="프로필" 
  content="홍길동" 
/>

<Button
  color="blue"
  onClick={handleClick}
>
  클릭
</Button>

title, content, color = props

똑같은 개념, 이름만 다름!

🔑 핵심 개념

컴포넌트 = 직접 만든 태그

<Card>, <Button> 같은 새 태그를 만드는 것

Props = HTML attributes

데이터를 태그에 전달하는 방법 (이미 써왔던 것!)

이름만 다를 뿐, 같은 개념

HTML: attributes / React: props

컴포넌트 안에서 props 사용하기

// components/Card.jsx
function Card({ title, content }) {
  // title = "프로필"
  // content = "홍길동"
  
  return (
    <div>
      <h3>{title}</h3>
      <p>{content}</p>
    </div>
  );
}

{'{title}'}, {'{content}'}로 props 값을 화면에 표시

📊 Before / After 비교

Before (반복) After (컴포넌트)
30줄 코드 3줄 코드
수정시 3곳 변경 수정시 1곳 변경
복사-붙여넣기 재사용
실수하기 쉬움 안전함

💻 실습 과제

팀원 프로필 카드를 만들어보세요:

  1. app/profile-ex/ProfileCard.jsx 파일 생성
  2. ProfileCard 컴포넌트 작성 (emoji, name, role props 받기)
  3. app/profile-ex/page.jsx에서 ProfileCard 3개 사용
  4. 브라우저에서 http://localhost:3000/profile-ex 확인

✨ 완성 화면 예시:

👨‍💻

김개발

프론트엔드 개발자

👩‍🎨

박디자인

UI/UX 디자이너

👨‍💼

이기획

프로젝트 매니저

💡 이모지, 이름, 직책을 자유롭게 바꿔보세요!