I needed to make a distributable global base config for the React version of chart.js that still allowed for local overriding. The nice thing about chart.js is that this is possible. On the other hand, it’s chaining-heavy, and the documentation for it is basic and lacks relevant use cases. The way to define one global property is to use the complete chained object for each setting, like Chart.defaults.interaction.mode = 'nearest'
. It gets a bit wordy and not too easy to compare with the local settings objects. But it’s nice to work with once we get the setup in place. If we only need the config in one project or app, we can add the defaults as mentioned directly in the topmost component, but in a design system setting it’s useful to be able to make something we can package and distribute.
Assuming that we have a sanely configured and working React project already, we start by installing chart.js and react-chartjs-2. This has been verified to work with version 3.8.0 and 4.2.0, respectively.
Make a function
#
Make a function that takes Chart as an argument and add your settings to it. I prefer to have the settings in a separate helpers.js file that can also contain other helpful chart objects such as colours and month names, so we need to export it.
export const chartBase = (Chart) => {
Chart.defaults.responsive = true
Chart.defaults.maintainAspectRatio = false
Chart.defaults.scale.grid.drawBorder = false
Chart.defaults.plugins.legend.align = 'start'
Chart.defaults.plugins.legend.position = 'bottom'
}
Import and use the function #
Import the function into either the component that holds the chart or, if you have multiple charts in an application, higher up in your component tree, so you don't have to do this in more than one place.
If we need to register any registerables, that must happen before we call the function.
Then we call the function with Chart
as an argument.
import { chartBase } from './helpers'
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)
chartBase(Chart)
Local adjustments #
In our global defaults, we set the legend at the bottom left. If we have a use case that needs it to be at the top right instead, we can override our global config. Most of the settings we define for chart.js are overrides of the default anyway.
import { Bar } from 'react-chartjs-2'
const ChartComponent = () => {
const options = {
plugins: {
legend: {
align: 'end',
position: 'top'
}
}
}
const data = {…}
return <Bar data={data} options={options} />
}
Chart.js can be a bit overwhelming when we have added all our options, overrides and callbacks, but stripping down the examples for this short guide might make the concept less complex. The advantage of using a global config is that we can quickly remove a few hundred lines of repetition in a project with a few different charts.