Card Compound Component

Overview

The Card compound component is a flexible container with standardized sections like header, body, footer, and image. It allows for consistent styling while providing flexibility in content arrangement.

Example

Card Image

Card Title

This is the card content. It can contain any React elements.

Another Card

Cards can be composed in different ways, with or without certain sections.

This flexibility is the beauty of compound components.

Card Image

File Title

This is the card content, it can contain any React elements.

Card Image

Card with Globe Title

This is the card content. It can contain any React elements.

Code Implementation

// Card.tsx
import React, { ReactNode } from 'react';
import Image from 'next/image';

// Main Card component
type CardProps = {
  children: ReactNode;
  className?: string;
};

const Card = ({ children, className = '' }) => {
  return (
    <div className={`bg-white dark:bg-gray-800 shadow-md rounded-lg overflow-hidden ${className}`}>
      {children}
    </div>
  );
};

// Header component
const Header = ({ children, className = '' }) => {
  return (
    <div className={`px-6 py-4 border-b border-gray-200 dark:border-gray-700 ${className}`}>
      {children}
    </div>
  );
};

// Body component
const Body = ({ children, className = '' }) => {
  return (
    <div className={`px-6 py-4 ${className}`}>
      {children}
    </div>
  );
};

// Footer component
const Footer = ({ children, className = '' }) => {
  return (
    <div className={`px-6 py-4 border-t border-gray-200 dark:border-gray-700 ${className}`}>
      {children}
    </div>
  );
};

// Image component
const CardImage = ({ src, alt, className = '' }) => {
  return (
    <div className={`w-full ${className}`}>
      <Image
        src={src} 
        alt={alt} 
        width={500}
        height={300}
        sizes="(max-width: 768px) 100vw, 500px"
        className="object-cover"
      />
    </div>
  );
};

// Attach sub-components to Card
Card.Header = Header;
Card.Body = Body;
Card.Footer = Footer;
Card.Image = CardImage;

export default Card;

Key Features

  • Modular design with separate components for header, body, footer, and image
  • Consistent styling across all card instances
  • Flexible composition - use only the parts you need
  • Clean separation of concerns between different sections
  • Easy to customize styles for individual card sections