reliya1541
@reliya1541 (Taewoong Lim)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Shad Cnをcostumizeの件

今しているプロジェクトではShadCnとtailwind 4.0 を使ってcostumizeしたいんですが、
tailwindを使っているのにstyleのtagを使うことについて質問があります。

コード

import * as React from "react";
import { cn } from "@/lib/utils";

const Input = React.forwardRef(
  ({ className, type = "text", placeholder, label, maxLength, width, ...props }, ref) => {

    const widthStyle = width ? { width: width } : { width: '16rem' };

    return (
      <div className={`relative`} style={widthStyle}>
        {label && (
          <div className="absolute left-2.5 top-1/2 transform -translate-y-1/2 text-muted-foreground">
            {label}
          </div>
        )}
        <input
          ref={ref}
          type={type}
          placeholder={placeholder}
          maxLength={maxLength}
          className={cn(
            "w-full rounded-xs bg-background h-10 border border-input px-3",
            label ? "pl-9" : "pl-4",
            className
          )}
          {...props}
        />
      </div>
    );
  }
);

Input.displayName = "Input";

export { Input };

質問

const widthStyle = width ? { width: width } : { width: '16rem' };

<div className={`relative`} style={widthStyle}>

ここでstyleで使うのはtailwindで求める方法ではないと考えています。

それでclassNameにcnのユーティリティクラスを使って見たんですが、適用されていないです。

<div className={cn("relative", size)}>

cnを使ってない方法でも試して見たんですが、それも適用されていないです。

<div className={`relative ${width ? `w-[${width}]` : 'w-64'}`}>

※ widthの違いを見てください

求める結果
image.png

求めない結果
image.png

質問
styleのタグ使わない方法はいないでしょうか?

0

1Answer

Tailwind ではクラス名を動的に(文字列結合やテンプレート文字列で)作ることはできません。クラス名は完全な形の文字列リテラルでソースコード中に書く必要があります。

  • :x: `w-[${width}]`
  • :x: "w-[" + width + "]"
  • :x: "w-[x]".replace("x", width)
  • :white_check_mark: "w-[16rem]"

詳しくは https://tailwindcss.com/docs/detecting-classes-in-source-files を見てください。

もし width の値が、計算で求めるなどして実行時に決まる場合は、 style を使う方法しかありません。逆に width の値があらかじめ分かっているなら、 <Input widthClass="w-[20rem]"> のようにクラス名で受け取って cn() に与えればいいです。

1Like

Comments

  1. @reliya1541

    Questioner

    ご親切な説明ありがとうございます。
    おかげで解決しました。

Your answer might help someone💌