[shadcn/ui] CardTitleのh3を他のタグ(h2など)に変更する方法

Next.js

shadcn/uiのCardTitleのh3を他のタグ(h2など)に変更する方法についてのメモです。初心者によるメモなので間違っている可能性があります。

ソースコード

/components/ui/card.tsを修正します。

変更前

const CardTitle = React.forwardRef<
    HTMLParagraphElement,
    React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
    <h3
        ref={ref}
        className={cn(
            "text-2xl font-semibold leading-none tracking-tight",
            className
        )}
        {...props}
    />
))

変更後

interface CardTitleProps extends React.HTMLAttributes<HTMLHeadingElement> {
    Tag?: React.ElementType
}

const CardTitle = React.forwardRef<
    HTMLParagraphElement,
    CardTitleProps
    // React.HTMLAttributes<HTMLHeadingElement>
>(({ className, Tag = 'h3', ...props }, ref) => (
    <Tag
    // <h3
        ref={ref}
        className={cn(
            "text-2xl font-semibold leading-none tracking-tight",
            className
        )}
        {...props}
    />
))

呼び出し側

<CardTitle
    Tag='h2'
    className='text-xl'
/>

ChatGPTに聞きながら修正して、よくわからないけどとりあえず動いたというコードなので参考程度にしてください。

広告