2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsでTailwindcssのcolorが反映されない

Posted at

問題

色を動的に変えたいcomponentがあって、tailwind.config.tsにcolorを設定していても真っ白になってしまうことがあった。

'use client';

import React from 'react';

import { ColorType } from '@/define/color';

type Props = {
  type: 'submit' | 'button';
  color: ColorType;
  name: string;
};

export const Button = (props: Props): React.JSX.Element => {
  const color = `border-${props.color}-500 bg-${props.color}-500 hover:border-${props.color}-700 hover:bg-${props.color}-700 focus:ring-${props.color}-200 disabled:border-${props.color}-300 disabled:bg-${props.color}-300`;

  return (
    <div className="flex flex-wrap justify-center gap-5">
      <button
        type={props.type}
        className={`${color} rounded-lg border px-5 py-2.5 text-center text-sm font-medium text-white shadow-sm transition-all focus:ring disabled:cursor-not-allowed`}
      >
        {props.name}
      </button>
    </div>
  );
};

解決方法

tailwind.config.tsにsafelistを追加することで色が反映されるようになった。

tailwind.config.ts
import colors from 'tailwindcss/colors';
import defaultTheme from 'tailwindcss/defaultTheme';

import type { Config } from 'tailwindcss';

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  safelist: [{ pattern: /^border-/ }, { pattern: /^bg-/ }, { pattern: /^text-/ }],
  theme: {
    extend: {
      // Set font family
      fontFamily: {
        sans: ['Inter', ...defaultTheme.fontFamily.sans],
      },
      // Set theme colors (Required config!)
      colors: {
        primary: colors.blue,
        secondary: colors.slate,
        green: colors.green,
        red: colors.red,
        blue: colors.blue,
        gray: colors.gray,
      },
    },
  },
  plugins: [require('@tailwindcss/typography'), require('@tailwindcss/forms')],
};
export default config;

原因

tailwindは未使用のcss classをpurgeするので色が未使用判定となり、cssクラスが定義されていない状態となってしまった。

備考

この記事の設定だと雑かもしれないので、本番に使う場合、もう少し精査した方がいいかもしれない。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?