Chartjs-Custom Tailwind CSS colors in chart.js

0👍

To use custom Tailwind colors in your Chart.js labels, you can follow these steps:

  1. Import the Tailwind CSS class names for your custom colors into your chart.jsx file. For example, if you have a custom color called labelColor defined in your Tailwind configuration, import its class name:
import 'tailwindcss/dist/tailwind.css'; // Import the Tailwind CSS file
import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

const Graph = ({ chartData }) => {
  // Rest of the code
}
  1. Modify the options object in your Graph component to use the custom color class names for your labels and ticks:
const options = {
  plugins: {
    legend: {
      display: true,
      labels: {
        usePointStyle: true,
        color: 'text-labelColor', // Use the class name for the custom color
      },
    },
  },
  scales: {
    x: {
      ticks: {
        display: true,
        color: 'text-labelColor', // Use the class name for the custom color
      },
    },
    y: {
      ticks: {
        display: true,
        color: 'text-labelColor', // Use the class name for the custom color
      },
    },
  },
};

Note that we prepend text- to the class name because Tailwind CSS uses the text- prefix for text-related styles.

  1. Update your JSX to apply the Tailwind CSS classes to the component:
return <Bar data={data} options={options} className="text-labelColor" />;

Here, we apply the text-labelColor class directly to the Bar component to ensure the custom color is used.

With these changes, your chart’s labels and ticks should now be styled using the custom colors defined in your Tailwind CSS configuration. Make sure to import the Tailwind CSS file at the beginning of your chart.jsx file to apply the styles correctly.

0👍

I don’t think you will be able to use custom colors that way as tailwind custom colors are used often more with class attributes and then the way you are trying to use them depends on the compatibility of the chart.js modules to accept color as a custom tailwind color variable.
another way you can approach this is by declaring all of your custom colors in a separate file and exporting them as variables and then you will be able to use them by importing that file.

Leave a comment