Skip to content

Instantly share code, notes, and snippets.

@gabrielmlinassi
Created November 16, 2022 19:49
Show Gist options
  • Save gabrielmlinassi/ba1d2c3dc134b9a7b86529f7232e6681 to your computer and use it in GitHub Desktop.
Save gabrielmlinassi/ba1d2c3dc134b9a7b86529f7232e6681 to your computer and use it in GitHub Desktop.
import React, { ReactNode } from 'react'
type CardProps = {
children: React.ReactNode
}
const Slots = {
image: null,
title: null,
content: null,
footer: null
}
const Card = ({ children }: CardProps) => {
React.Children.forEach(children, (child) => {
if (React.isValidElement(child)) {
switch (child.type.displayName) {
case 'CardHeader':
React.Children.forEach(child.props.children, (child) => {
if (React.isValidElement(child)) {
switch (child.type.displayName) {
case 'CardImage':
Slots.image = child
break
}
}
})
break
case 'CardBody':
React.Children.forEach(child.props.children, (child) => {
if (React.isValidElement(child)) {
switch (child.type.displayName) {
case 'CardTitle':
Slots.title = child
break
case 'CardContent':
Slots.content = child
break
}
}
})
break
case 'CardFooter':
Slots.footer = child
break
}
}
})
return (
<div className="overflow-hidden w-[400px] bg-white rounded-xl drop-shadow-card">
{Slots.image}
<div className="px-5 pt-5 pb-10 text-secondary">
<div>
{Slots.title}
{Slots.content}
{Slots.footer}
</div>
</div>
</div>
)
}
const CardHeader = ({ children }: { children: ReactNode }) => {
return <>{children}</>
}
const CardImage = ({ children }: { children: ReactNode }) => {
return <div className="relative h-[225px]">{children}</div>
}
const CardBody = ({ children }: { children: ReactNode }) => {
return <>{children}</>
}
const CardTitle = ({ children }: { children: ReactNode }) => {
return <h3 className="font-serif text-3xl font-normal">{children}</h3>
}
const CardContent = ({ children }: { children: ReactNode }) => {
return <div className="mt-3">{children}</div>
}
const CardFooter = ({ children }: { children: ReactNode }) => {
return <div className="mt-4">{children}</div>
}
CardHeader.displayName = 'CardHeader'
CardImage.displayName = 'CardImage'
CardBody.displayName = 'CardBody'
CardTitle.displayName = 'CardTitle'
CardContent.displayName = 'CardContent'
CardFooter.displayName = 'CardFooter'
Card.Header = CardHeader
Card.Image = CardImage
Card.Body = CardBody
Card.Title = CardTitle
Card.Content = CardContent
Card.Footer = CardFooter
export default Card
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment