Could not find a declaration file for module chartjs-plugin-stacked100 - reactjs

I am trying to use chartjs-plugin-stacked100 in a React App:
import React, { useEffect, useState } from 'react';
import { Chart } from 'react-chartjs-2';
import ChartjsPluginStacked100 from 'chartjs-plugin-stacked100';
const ConnectedTime = () => {
// https://designcode.io/react-hooks-handbook-usestate-hook
// https://designcode.io/react-hooks-handbook-fetch-data-from-an-api
useEffect(() => { }, []);
return <>
{
<div>
<ChartjsPluginStacked100
type="bar"
data={{
labels: ["Foo", "Bar"],
datasets: [
{ label: "bad", data: [5, 25], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "better", data: [15, 10], backgroundColor: "rgba(255, 235, 59, 0.6)},
{ label: "good", data: [10, 8], backgroundColor: "rgba(100, 181, 246, 0.6)" }]
}}
options={{
indexAxis: "y",
plugins: {
stacked100: { enable: true }
}
}} />
</div>
}
</>
}
export default ConnectedTime
When I yarn start this piece of code, I get the error:
TypeScript error in /home/mihamina/.../src/Components/ConnectedTime/ConnectedTime.tsx(4,37):
Could not find a declaration file for module 'chartjs-plugin-stacked100'.
'/home/mihamina/.../node_modules/chartjs-plugin-stacked100/build/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/chartjs-plugin-stacked100` if it exists
or add a new declaration (.d.ts) file containing
`declare module 'chartjs-plugin-stacked100';`
Issuing npm i --save-dev #types/chartjs-plugin-stacked100 : The package does not exist.
I dont quite understand about the .d.ts file:
Do I create it at the root of the project? (same folder as package.json?)
Is the required name really .d.ts or should I prepend the name with chartjs-plugin-stacked100?

I managed to make it work:
Create a global.d.ts and declare the module
Use the Bar component
Content of global.d.ts:
declare module 'chartjs-plugin-stacked100';
declare module 'chartjs-plugin-stacked100'{
export function ChartjsPluginStacked100(): function
}
Use of Bar:
import { Chart, Bar } from 'react-chartjs-2';
import ChartjsPluginStacked100 from 'chartjs-plugin-stacked100';
Chart.register(ChartjsPluginStacked100);
const ChartData = (props: any) => {
return <>
{
<div>
<Bar
data={{
labels: ["Foo", "Bar"],
datasets: [
{ label: "bad", data: [5, 25], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "better", data: [15, 10], backgroundColor: "rgba(255, 235, 59, 0.6)" },
{ label: "good", data: [10, 8], backgroundColor: "rgba(100, 181, 246, 0.6)" }]
}}
options={{
indexAxis: "y",
plugins: {
stacked100: { enable: true }
}
}} />
</div>
}
</>
};
export default ChartData
I updated the documentation and requested a pull at: https://github.com/y-takey/chartjs-plugin-stacked100/pull/48 , where I wrote a small sample React app that uses the plugin.

Related

React react-chartjs-2 adding x and y axis labels to a line graph

import React from "react";
import { Line } from "react-chartjs-2";
// "chart.js": "^2.9.4",
// "react-chartjs-2": "^2.11.1"
const ext_data = [11, 19, 3, 5, 2, 3, 14, 19];
const ll = Array.from(Array(ext_data.length).keys());
const data = {
labels: ll,
datasets: [
{
label: "Profit$",
data: ext_data,
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.4)"
}
]
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
};
const LineChart = () => (
<>
<div className="header">
<h1 className="title">Profit Trend</h1>
<div className="links"></div>
</div>
<Line data={data} options={options} />
</>
);
export default LineChart;
I am trying to add x-axis name : "time" and y-axis name: "number of cars".
I went into the documentation : https://www.chartjs.org/docs/latest/axes/labelling.html
However, I was not able to find something that was useful.
Thank you for your time.
In react-chartjs-2, to add your title to your axis, just add this to your yAxes array of options (options.scales.yAxes[]):
scaleLabel: {
display: true,
labelString: "number of cars",
fontColor: "color you want",
}
same for your xAxes.

I want to change the position and style of the label in the React chart

I am using react-chartjs-2. I want to display the position of the label below the graph. Also, the shape of the label is currently square, but I would like to change it to a round shape. I specified option and position: bottom, but the position of the label did not change.
import "./styles.css";
import React from "react";
import { Bar } from "react-chartjs-2";
const data = [
{
label: "a",
data: [56, 23, 55, 56, 57]
},
{
label: "b",
data: [22, 17, 32, 47, 62]
},
{
label: "c",
data: [46, 73, 25, 76, 27]
}
];
const App = () => {
const CHART_COLORS = ["#e35b2c", "#e77235", "#eb8a40"];
const list = data.map((d, index) => {
return {
label: d.label,
backgroundColor: CHART_COLORS[index],
data: d.data,
stack: 1
};
});
const options = {
legend: {
position: "bottom"
}
};
return (
<>
<div className="App">
<Bar
data={{
labels: ["block1", "block2", "block3"],
datasets: list
}}
width={100}
height={50}
options={options}
/>
</div>
</>
);
};
export default App;
Legend option is changed in latest version of chartjs to,
Namespace: options.plugins.legend
plugins: {
legend: {
position: "bottom",
labels: {
usePointStyle: true //for style circle
}
}
}
};
You can check working demo here, https://codesandbox.io/s/react-chartjs-legend-option-prbgb
Reference : https://www.chartjs.org/docs/latest/configuration/legend.html

How to use chartjs-plugin-trendline with react-chartjs-2

I want to add 'Trend' line to my line chart. I am using react-chartjs-2 to draw charts on my website. The code looks like:
import { Line } from 'react-chartjs-2';
import trendlineLinear from 'chartjs-plugin-trendline';
const PatientInfectionChart = ({ data, labels }) => {
const datasets = [
{
data: data.totalInfected,
backgroundColor: 'rgb(233, 85, 0)',
borderColor: 'rgba(233, 85, 0, 0.7)',
label: 'Today Infected',
},
{
data: data.todayRecovered,
backgroundColor: 'rgb(23, 198, 113)',
borderColor: 'rgba(23, 198, 113, 0.7)',
label: 'Today Recovered',
trendlineLinear: {
style: 'rgb(23, 198, 113)',
lineStyle: 'dotted',
width: 2,
},
},
];
return (
<Line
data={{ datasets, labels }}
plugins={[trendlineLinear]}
options={{
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
},
}}
/>
);
};
export default PatientInfectionChart;
However, I get the following error:
Uncaught TypeError: Cannot read property 'ctx' of undefined
at Object.afterDraw (chartjs-plugin-trendline.js:23)
at callback (helpers.segment.js:89)
at PluginService._notify (chart.esm.js:4737)
at PluginService.notify (chart.esm.js:4724)
at Chart.notifyPlugins (chart.esm.js:5788)
at Chart.draw (chart.esm.js:5537)
at chart.esm.js:66
at Map.forEach (<anonymous>)
at Animator._update (chart.esm.js:44)
at chart.esm.js:34
How to I fix this?
The trendline plugin requires chart.js version 2, react chart.js uses version 3 so you will need to downgrade react-chartjs
Commands:
yarn remove react-chartjs-2
yarn add react-chartjs-2#2.11.2

How to show data value on top of bar in react-chartjs-2?

I made bar chart in react-chartjs-2. I want to show data value of each bar on the top of the bar. For that I used the plugin calls chartjs-plugin-datalabels But it's not showing anything.
is it possible to show each value of bar chart ?
I want to show data value somethings like this.
Here is my code.
import React, { Component } from "react";
import "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
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]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Any help would be appreciated.
import React, { Component } from "react";
import Chart from "chart.js/auto";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
componentDidMount() {
Chart.register(ChartDataLabels);
}
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
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]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black",
formatter: Math.round,
anchor: "end",
offset: -20,
align: "start"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Here you can see in componentDidMount we have registered chart data label plugin for displaying data.
And another thing is in the options added few more parameters as per below field
anchor: "end",
offset: -20,
align: "start"
This is used for displaying data in the top.
The react-chartjs-2 package holds a plugin property which can be set on the components.
Change the import from:
import "chartjs-plugin-datalabels";
to:
import ChartDataLabels from 'chartjs-plugin-datalabels';
On your component, add the plugin variable which holds the imported value.
from:
<Line data={data} options={options} />
to:
<Line data={data} plugins={[ChartDataLabels]} options={options} />
See this original stackoverflow answer to the similar question
use this "chartjs-plugin-datalabels": "^0.5.0" version
it works for me
Here is working example
https://codesandbox.io/s/barchart-knycb
const options2 = {
plugins: {
datalabels: {
anchor: "end",
align: "start",
formatter:(value,context)=>{
const datasetArray = []
context.chart.data.datasets.forEach((dataset)=>{
if(dataset.data[context.dataIndex] != undefined){
datasetArray.push(dataset.data[context.dataIndex])
}
})
function totalSum(total, datapoint){
return total + datapoint;
}
let sum = datasetArray.reduce(totalSum,0)
if(context.datasetIndex == datasetArray.length-1)
return sum
else
return ''
},
},
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked',
},
},
responsive: true,
scales: {
x: {
stacked: true,
ticks: {
maxRotation: 70,
minRotation: 70
}
},
y: {
stacked: true,
},
},
};
const data1 = {
labels,
datasets: [
{
label: 'Dataset One',
data: [1,2,3,4,5,6,7],
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Dataset Two',
data: [1,8,3,4,9,6,7],
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};

Why is this bar chart using chart.js not rendering in react.js?

I'm trying to add a bar chart to my app with arbitrary data for now but I can't get it to render. The it's imported correctly and i've used example code from the chart.js web site but no luck. What am I missing?
import Chart from 'chart.js';
import React, { Component } from 'react';
class ChartTeamOne extends Component {
setState(){
const t1ChartEl= document.getElementById("teamOneCanvas");
let teamOneChart = new Chart(t1ChartEl,{
type: 'bar',
data: {
labels: ["Red", "Blue"],
datasets: [{
label: '# of Votes',
data: [12, 19],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
render(){
return(
<canvas id="teamOneCanvas"></canvas>
);
}
}
export default ChartTeamOne;
This is because you have this in the setState function and this is not setting the state of anything. This should be in the componentDidMount() lifecycle function.
setState() is used to update the state of your application https://facebook.github.io/react/docs/component-api.html where as componentDidMount() will fire once your component is mounted after the initial rendering occurs and will perform the functions inside. https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount
chart.js needs a canvas to "overwrite" before it can draw its chart. You have the part where you return the canvas correct. But the function you are looking for is componentDidMount()not setState(). I have taken their example for pie charts and created a react class for it. It should be pretty simple to change your code to match the change.
import Chart from 'chart.js';
import React, {
Component
} from 'react';
export default class PieChart extends Component {
componentDidMount() {
debugger;
const ctx = document.getElementById("pie-chart");
const data = {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF0000",
"#0000FF",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
const pieChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
render() {
return (
<canvas id="pie-chart"></canvas>
);
}
}

Resources