Chartjs-How to set additional options for Chart.js BarCharts using React-Chartkick

2👍

Well, I used the same node package in a project with different approach kinda work for me. Almost all the charts take the same attributes.

Basically, this attribute dataset={{ backgroundColor: ['white', 'yellow' ], }}
is all you need to colour each bar. You can either pass string or array of string to backgroundColor.

The backgroundColor in dataset takes two types of data String and Array(object). Typical examples of passing data are below.

  1. When you set backgroundColor to a string, it applied the same colour to each bar. e.g backgroundColor: 'red'

BarChart – <BarChart dataset={{ backgroundColor: 'red', }} />

bar chart one color]

  1. When you set backgroundColor to an array, it applied each colour in the array to each bar. e.g backgroundColor: ['red', 'yellow'], then you create a loop of colours base on the data length.

column chart – <ColumnChart dataset={{ backgroundColor: ['red', 'yellow' ], }} />

enter image description here

React Implementation Below:

/* eslint-disable no-plusplus */
 import React from 'react';
 import { ColumnChart, BarChart } from 'react-chartkick';
 import { chartOne } from '../common/chartData';
 import 'chart.js';

 const MonthlyGrowth = () => {
    const handleBgColors = () => {
       const firstColor = "#A00B16", secondColor = "#FAA226";
       const arrOfBgColors = [];
       for (let i = 1; i <= chartOne.length; i++) {
           if (i % 2 === 0) {
              arrOfBgColors.push(secondColor)
           } else {arrOfBgColors.push(firstColor)}
       }
       return arrOfBgColors;
   }

   return (
     <div className="bukka-card uk-card-default bg-white pt-4 pb-2 mr-1 pl-3 pr-2 pl- 
       lg-5">
        <h2 className="mt-2">4,500,000</h2>
        <BarChart
           dataset={{ borderWidth: 0, width: 0, backgroundColor: handleBgColors(), }}
           data={chartOne}
        />
      </div>
    )
}

export default MonthlyGrowth;

Leave a comment