I'm trying to create a ref to the chart I'm building with chart.js and react-chartjs-2.
Here's the line where I'm trying to create the ref specifying the type: const chartRef = useRef<Line>(null);
And this is the error I get:
'Line' refers to a value, but is being used as a type here. Did you mean 'typeof Line'?
I found the following documentation but since I'm new to TypeScript I don't know how to interpret it yet. Here's the complete code I'm using:
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { useRef } from "react";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [
{
label: "First dataset",
data: [33, 53, 85, 41, 44, 65],
fill: true,
backgroundColor: "rgba(75,192,192,0.2)",
borderColor: "rgba(75,192,192,1)"
},
{
label: "Second dataset",
data: [33, 25, 35, 51, 54, 76],
fill: false,
borderColor: "#742774"
}
]
};
export default function App() {
const chartRef = useRef<Line>(null);
return (
<div className="App">
<h1>This is a chart.</h1>
<Line data={data} ref={chartRef} />
</div>
);
}
Can you point me in the right direction? Thanks!
I'm not terribly familiar with ChartJS, but when I changed your existing code from const chartRef = useRef<Line>(null); to const chartRef = useRef<'line'>(null); (per the docs), the linter gave me a better idea as to the what needed to be fixed (on the ref).
In your case:
export function App() {
const chartRef = useRef<ChartJS<"line", number[], string>>(null);
return (
<div className="App">
<h1>This is a chart.</h1>
<Line data={data} ref={chartRef} />
</div>
);
}
Working CodeSandbox
Related
I want the user to add data to a Radar Chart in React through User Input. I tried different methods but it just does not work or the chart does not get displayed. Here is the code
import './App.css';
import React from 'react'
import {
Chart as ChartJS,
RadialLinearScale,
PointElement,
LineElement,
Filler,
Tooltip,
Legend
} from "chart.js";
import { Radar } from "react-chartjs-2";
function App() {
ChartJS.register(
RadialLinearScale,
PointElement,
LineElement,
Filler,
Tooltip,
Legend
);
const data = {
labels: ["Business 1", "Business 2", "Business 3"],
datasets: [
{
label: "Number of Businesses",
data: [1300, 400, 160],
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 1
}
]
};
return (
<div className='App'>
<Radar data={data} />
<form>
<input type='text' placeholder='Label' />
<input type='text' placeholder='Dataset' />
<button>Add Data</button>
</form>
</div>
);
}
export default App;
I would really appreciate any help or solution.
I've looked everywhere online and I can't find a way to select a dataset where it won't remove or hide the dataset(because I want you to be able to select the others).
This is ChartJS in React so I'm using the react-chartjs wrapper.
Here is how the example looks:
And I want to be able to click on dataset 1 and then dataset 2 and dataset 3 get greyed out(not deleted), basically showing that dataset 1 was selected.
I've put a sandbox together: https://codesandbox.io/s/chartjs-select-dataset-r1kixh
I'm unable to update the color and I'm assuming with the way I have it that if I was able to update the color I probably wouldn't be able to get back the original color unless I find a way to re-render it? Not sure how I could also deselect all?
TL;DR:
How to select one dataset without removing the other?
How to be able to select a different dataset(hence using its original color)
How to "reset" the colors by deselecting(clicking in the space where there isn't a graph maybe)
The first two questions are this stack overflow question.
Here is the code:
import React, { MouseEvent, useRef } from "react";
import {
Chart as ChartJS,
LinearScale,
CategoryScale,
BarElement,
PointElement,
LineElement,
Legend,
Tooltip
} from "chart.js";
import { Chart, getDatasetAtEvent } from "react-chartjs-2";
import faker from "faker";
ChartJS.register(
LinearScale,
CategoryScale,
BarElement,
PointElement,
LineElement,
Legend,
Tooltip
);
export const options = {
scales: {
y: {
beginAtZero: true
}
}
};
const labels = ["January", "February", "March", "April", "May", "June", "July"];
export const data = {
labels,
datasets: [
{
type: "line" as const,
label: "Dataset 1",
backgroundColor: "rgba(75, 192, 192, 1)",
borderColor: "rgba(255, 99, 132,1)",
borderWidth: 2,
fill: false,
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 }))
},
{
type: "bar" as const,
label: "Dataset 2",
backgroundColor: "rgba(75, 192, 192, 1)",
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
borderColor: "white",
borderWidth: 2
},
{
type: "bar" as const,
label: "Dataset 3",
backgroundColor: "rgba(53, 162, 235, 1)",
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 }))
}
]
};
export function App() {
const chartRef = useRef<ChartJS>(null);
const onClick = (event: MouseEvent<HTMLCanvasElement>) => {
const { current: chart } = chartRef;
const element = getDatasetAtEvent(chart, event);
const datasetIndex = element[0].datasetIndex;
const selectedDataset = data.datasets[datasetIndex].label;
if (!chart) {
return;
}
console.log("SELECTED: ", selectedDataset);
for (let i = 0; i < data.datasets.length; i++) {
if (data.datasets[i].label !== selectedDataset) {
console.log("NOT SELECTED: ", data.datasets[i].label);
data.datasets[i].backgroundColor = "rgba(255,255,255,0.2)";
}
}
chartRef.current.update();
};
return (
<Chart
ref={chartRef}
type="bar"
onClick={onClick}
options={options}
data={data}
/>
);
}
Thanks for any help!
I can't seem to fix this error which is only happening after I've deployed and it's driving me crazy. I've tried everything from all other stack overflow suggestions with no luck. I get no errors on local, however when I deploy to Heroku I get the error
"Error: "line" is not a registered controller." Any ideas?
import React, { useState } from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
PointElement,
LineElement,
} from 'chart.js';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
);
import { Chart } from 'react-chartjs-2';
const staticData = [
{
type: 'line',
label: 'Macleay Island Avg',
backgroundColor: '#38A169',
borderColor: '#38A169',
order: 1
},
{
type: 'bar',
label: 'Macleay Island Total',
backgroundColor: '#C6F6D5',
order: 3
},
{
type: 'line',
label: 'Russell Island Avg',
backgroundColor: '#F56565',
borderColor: '#F56565',
order: 2
},
{
type: 'bar',
label: 'Russell Island Total',
backgroundColor: '#FED7D7',
borderColor: 'rgb(14, 142, 205)',
order: 4
}
]
return (
<>
<Chart type='bar' data={graphData} />
</>
)
You need to import and register the LineController
I am making a dashboard with react, I want to have doughnut charts that display some information. I am following this tutorial that uses chartjs and I have ran into an unexpected problem.
When I run my app, the dashboard does not display the doughnut chart,
however if I add a Line graph or bar chart, they display as expected
This is the dashboard when trying to rendering a doughnut chart, I have circled what I think is the canvas for the chart
This is the code
import React from 'react';
import {Pie, Doughnut} from 'react-chartjs-2';
const state = {
labels: ['January', 'February', 'March',
'April', 'May'],
datasets: [
{
label: 'Rainfall',
backgroundColor: [
'#B21F00',
'#C9DE00',
'#2FDE00',
'#00A6B4',
'#6800B4'
],
hoverBackgroundColor: [
'#501800',
'#4B5000',
'#175000',
'#003350',
'#35014F'
],
data: [65, 59, 80, 81, 56]
}
]
}
export default class App extends React.Component {
render() {
return (
<div>
<Doughnut
data={state}
options={{
width:"400",
height:"400",
responsive: true,
maintainAspectRatio: true,
title:{
display:true,
text:'Average Rainfall per month',
fontSize:20
},
legend:{
display:true,
position:'right'
}
}}
/>
</div>
);
}
}
I have looked at the following solution found on the following
question, but it is still not working. Note that the pie chart is also not displaying correctly, only bar and line charts display correctly
Can't resize react-chartjs-2 doughnut chart
TL;DR: Chart-js in react not showing doughnut chart but other charts work.
I am trying to display a graph using the library Chart.js.
My data are in the format:
data: [["15-11-2019", 25], ["16-11-2019", 35], ["17-11-2019", 40], ["18-11-2019", 20], ["19-11-2019", 15]]
I am not able to transform the x-Axis in a time-axis.
I tried to pass in the options parameter the time type but it does not seem to work.
The graph renders, but the x-axis does not exists, only the y-axis exists.
import React, {Component, useState, useEffect, useCallback} from 'react';
import Plot from 'react-plotly.js';
import { Chart } from 'react-charts'
function MyChart() {
const data = React.useMemo(
() => [
{
label: 'Series 1',
data: [["15-11-2019", 25], ["16-11-2019", 35], ["17-11-2019",40], ["18-11-2019", 20], ["19-11-2019", 15]]
}],
[]
)
const axes = React.useMemo(
() => [
{ primary: true, type: 'linear', position: 'bottom' },
{ type: 'linear', position: 'left' },
],
[]
)
const options = React.useMemo(
() => [
{
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
],
[]
)
return (
// A react-chart hyper-responsively and continuusly fills the available
// space of its parent element automatically
<div
style={{
width: '600px',
height: '500px'
}}
>
<Chart data={data} axes={axes} options={options}/>
</div>
)
}
export default MyChart;
Update: See this specific line about format in the documentation
The x-axis data points may additionally be specified via the t or x attribute when using the time scale.
See more here https://www.chartjs.org/docs/latest/axes/cartesian/time.html
Your datafield must be a dictionary/object of x, y values:
data: [{x: "2019-01-03", y: 15}, {x: "2019-01-04", y: 18}, ...]
When creating your chart, set type in options.scales:
...,
options: {
scales: {
xAxes: [{
type: 'time',
}]
},
...