0
0

Tailwind CSSをNext.jsで使用してみた

Posted at

この記事を見て、Animataの中にあるflip-cardを試してみようと思ったら日本語の記事がなく思ったよりセットアップに時間がかかったので備忘録としてまとめておく

目標

以下のようなカードを作成する

セットアップさえできればこのページのコードをコピペするだけで導入できる

operationcheck.gif

環境

  • Windows 11
  • VSCode
  • npm

各ツールのインストール方法については割愛

手順


1.プロジェクトを作成

下記コマンドでNext.jsのひな型ファイルを作成

npx create-next-app my-project

※typescript・eslint・approuterをYESにしておく


2.Tailwind CSSのインストール

フォルダに移動後

下記コマンドでパッケージをインストール

npm install -D tailwindcss postcss autoprefixer

下記コマンドでtailwind.config.jsを作成

npx tailwindcss init -p

作成したtailwind.config.jsに以下のように記載

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
 
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

3.CSSの追加

globals.cssの中身を削除して以下のように記載

@tailwind base;
@tailwind components;
@tailwind utilities;

  • 余談

    この時下記のように波線で表示される

    スクリーンショット 2024-07-27 001700.png


    これでもとくに問題はないが気になる場合は下記の拡張機能をインストールすれば解消される

    スクリーンショット 2024-07-27 001712.png

    スクリーンショット 2024-07-27 001743.png

4.設定ファイルの設定

tsconfig.jsonに以下を追加(baseUrlを追加することになるはず

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"]
    }
  }
}

5.その他animataの起動に必要なパッケージのインストールとファイルを作成

下記コマンドでパッケージをインストール

npm install tailwind-merge clsx lucide-react tailwindcss-animate

tailwind.config.jsに以下のようにプラグインを追加

module.exports = {
  plugins: [require("tailwindcss-animate")],
};


app以下にlib/utils.tsを作成し以下のように記載

import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
 
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

6.コードを記載

この記事を参考に

components/animata/card/flip-card.tsxを作成して以下のように記載

import { cn } from "@/lib/utils";

interface FlipCardProps extends React.HTMLAttributes<HTMLDivElement> {
  image: string;
  title: string;
  description: string;
  subtitle?: string;
  rotate?: "x" | "y";
}

export default function FlipCard({
  image,
  title,
  description,
  subtitle,
  rotate = "y",
  className,
  ...props
}: FlipCardProps) {
  const rotationClass = {
    x: ["group-hover:[transform:rotateX(180deg)]", "[transform:rotateX(180deg)]"],
    y: ["group-hover:[transform:rotateY(180deg)]", "[transform:rotateY(180deg)]"],
  };
  const self = rotationClass[rotate];

  return (
    <div className={cn("group h-72 w-56 [perspective:1000px]", className)} {...props}>
      <div
        className={cn(
          "relative h-full rounded-2xl transition-all duration-500 [transform-style:preserve-3d]",
          self[0],
        )}
      >
        {/* Front */}
        <div className="absolute h-full w-full [backface-visibility:hidden]">
          <img
            src={image}
            alt="image"
            className="h-full w-full rounded-2xl object-cover shadow-2xl shadow-black/40"
          />
          <div className="absolute bottom-4 left-4 text-xl font-bold text-white">{title}</div>
        </div>

        {/* Back */}
        <div
          className={cn(
            "absolute h-full w-full rounded-2xl bg-black/80 p-4 text-slate-200 [backface-visibility:hidden]",
            self[1],
          )}
        >
          <div className="flex min-h-full flex-col gap-2">
            <h1 className="text-xl font-bold text-white">{subtitle}</h1>
            <p className="mt-1 border-t border-t-gray-200 py-4 text-base font-medium leading-normal text-gray-100">
              {description}{" "}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}


page.tsxの中身を削除して以下のように記載

import FlipCard from "@/components/animata/card/flip-card"

export default function Home() {
  return (
    <div>
      <FlipCard
        description="Computer programming or coding is the composition of sequences of instructions, called programs, that computers can follow to perform tasks."
        image=" https://images.unsplash.com/photo-1525373698358-041e3a460346?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3"
        rotate="y"
        subtitle="What is programming?"
        title="Programming"
      />
    </div>
  )
}

7.コードを実行

以下のコマンドを実行し、正しく出力されているかを確認

npm run dev

まとめ

今回初めてTailwind CSSを使用してみた

各参考サイトを個別に見ただけではセットアップができず思ったより導入で時間がとられたが、完了してしまえばクリエイティブなボタンやカードといった素晴らしいデザインを簡単に導入することができ、自作のアプリでもクオリティの高いUIが導入できる素晴らしいツールだと感じた

今までフロントエンド、特にCSSに悩まされてきたので今後はぜひとも活用したい


以上、何かご質問やご不明点・追記などありましたら

お気軽にコメントください


参考サイト

これはすごい便利! WebサイトやスマホアプリのUIに今時のアニメーションやインタラクションを簡単に実装できる -Animata

Install Tailwind CSS with Next.js

animataのセットアップについて

Flip Cardのページ

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