0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

tailwind-mergeは競合するTailwind CSSクラスを解決してくれるライブラリです。
同じTailwind CSSクラスが指定された際に役立ちます。

ゴール

tailwind-mergeを使ってReactコンポーネントを作成する。

環境

  • React:18.3.1
  • Vite:5.3.1
  • tailwindcss:3.4.4
  • tailwind-merge:2.3.0

Viteを利用したReactとtailwindcssの環境構築は下記の記事が参考になります。

tailwind-merge のインストール

tailwind-mergeをインストールします。

npm i tailwind-merge

使い方

次の例ではtext-red-600text-black-600が競合していますが、tailwind-mergeが後者を優先してくれます。このように競合するTailwindCSSのクラスをマージする事ができます。

// 結果は 'bg-blue-500 text-white'
const mergedClassName = twMerge('text-red-600 text-white', 'text-black-600');

コンポーネント化して使ってみる

twMergeを使用し次のようにReactコンポーネントを作成します。
className 属性には、twMerge を使ってデフォルトのクラス(第一引数)と動的な className(第二引数) をマージした結果を設定します。

sample.tsx
import { ReactNode } from 'react';
import { twMerge } from 'tailwind-merge';


interface ButtonProps {
  className: string;
  children: ReactNode;
}

const Button = ({ className, children } : ButtonProps) => {
    return (
      <button className={twMerge('px-4 py-2 font-light bg-blue-300 mt-5', className)}>
        {children}
      </button>
    );
};
  
export default Button;

上記作成した Sample コンポーネントを表示します。
Sample コンポーネントではデフォルトのクラスとマージされ、px-4 py-2 bg-green-500 font-bold mt-10 が適用されます。

App.tsx
import Sample from './Sample';

function App() {

  return (
    <div className="flex flex-col items-center justify-center min-h-screen">
      <h1 className='font-bold text-4xl	'>Hello World!</h1>
      {/* 結果は px-4 py-2 bg-green-500 font-bold mt-10 が適用*/  }
      <Sample className="bg-green-500 font-bold mt-10">ボタン</Sample>
    </div>
  )
}

export default App

実行結果

次のコマンドで実際にブラウザで確認してみると、px-4 py-2 bg-green-500 font-bold mt-10が適用されてることを確認できました。

npm run dev

image.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?