When I create a line chart with chart.js everything works fine, but when I try to create a bar chart it shows a white background. Please help. This is my working code (Line Chart.js)
import React from 'react';
import { useEffect, useState } from "react";
import { Line, Bar } from 'react-chartjs-2';
export function BarChart() {
const [chartData, chartDataSet] = useState(null);
useEffect( () => {
const data = {
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
chartDataSet(data);
}, []);
if (!chartData) {
return null;
}
return <Line data={chartData}/>;
}
This code don't work and generate nothing (bar chart.js):
import React from 'react';
import { useEffect, useState } from "react";
import { Line, Bar } from 'react-chartjs-2';
export function BarChart() {
const [chartData, chartDataSet] = useState(null);
useEffect( () => {
const data = {
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
chartDataSet(data);
}, []);
if (!chartData) {
return null;
}
return <Bar data={chartData}/>;
}
I run everything in a new file at this place:
export function Mytest() {
return (
<div className="App">
<BarChart/>
</div>
);
}
Problem solved. You had to add some extra imports and add them to the register.
Working code (bar chart.js):
import React from 'react';
import {Bar} from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
Title,
Tooltip,
Legend,
BarElement,
BarController
} from 'chart.js'
import { Chart } from 'react-chartjs-2'
ChartJS.register(
CategoryScale,
Title,
Tooltip,
Legend,
BarElement,
BarController
)
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
export function BarChart() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
width={100}
height={50}
options={{
maintainAspectRatio: true
}}
/>
</div>
);
}