← 돌아가기

Step 4: 컴포넌트 재사용

😢 문제: 버튼이 반복됨

// 중복 코드 😢
<button className="px-4 py-2 bg-blue-500 text-white rounded">
  변경
</button>
<button className="px-4 py-2 bg-red-500 text-white rounded">
  삭제
</button>
<button className="px-4 py-2 bg-green-500 text-white rounded">
  추가
</button>

❌ 같은 코드 반복

❌ 수정할 때 여러 곳 변경 필요

❌ 유지보수 어려움

✅ 해결: Button 컴포넌트

1️⃣ 컴포넌트 만들기

// components/Button.jsx
export default function Button({ children, color, onClick }) {
  return (
    <button
      onClick={onClick}
      className={`px-4 py-2 bg-${color}-500 text-white rounded 
                  hover:bg-${color}-600`}
    >
      {children}
    </button>
  );
}

2️⃣ 사용하기

"use client";
import Button from "@/components/Button";

export default function Page() {
  return (
    <div className="flex gap-2">
      <Button color="blue" onClick={() => alert("변경")}>
        변경
      </Button>
      <Button color="red" onClick={() => alert("삭제")}>
        삭제
      </Button>
      <Button color="green" onClick={() => alert("추가")}>
        추가
      </Button>
    </div>
  );
}

📌 핵심

  • ✅ 반복 코드 제거
  • ✅ 재사용 가능
  • ✅ 유지보수 쉬움
  • props로 데이터 전달

🎯 Props 이해하기

Props 전달 (부모)

<Button 
  color="blue" 
  onClick={() => alert("클릭")}
>
  변경
</Button>

Props 받기 (자식)

function Button({ 
  children,  // "변경"
  color,     // "blue"
  onClick    // () => alert("클릭")
}) {
  return (...)
}

💡 Props란?

컴포넌트에 데이터를 전달하는 방법

  • children: 태그 사이 내용
  • color, onClick: 직접 전달한 값

💻 실습: Card 컴포넌트

1️⃣ 컴포넌트 만들기

// 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️⃣ 사용하기

import Card from "@/components/Card";

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

프로필

홍길동

나이

25세

직업

개발자

📁 프로젝트 구조

my-first-nextjs/
  app/
    page.jsx              // 홈 (네비게이션)
    text-change/
      page.jsx            // 텍스트 변경
    toggle/
      page.jsx            // 토글
    counter/
      page.jsx            // 카운터
    layout.jsx
  components/
    Button.jsx            // 재사용 버튼
    Card.jsx              // 재사용 카드
  public/
  package.json