-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathApp.tsx
More file actions
93 lines (80 loc) · 1.99 KB
/
App.tsx
File metadata and controls
93 lines (80 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import React, { useRef, useEffect, useState } from 'react';
import type { ChartData, ChartArea } from 'chart.js';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
Legend,
} from 'chart.js';
import { Chart } from 'react-chartjs-2';
import { faker } from '@faker-js/faker';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
Legend
);
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
const colors = [
'red',
'orange',
'yellow',
'lime',
'green',
'teal',
'blue',
'purple',
];
export const data = {
labels,
datasets: [
{
label: 'Dataset 1',
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
},
{
label: 'Dataset 2',
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
},
],
};
function createGradient(ctx: CanvasRenderingContext2D, area: ChartArea) {
const colorStart = faker.random.arrayElement(colors);
const colorMid = faker.random.arrayElement(
colors.filter(color => color !== colorStart)
);
const colorEnd = faker.random.arrayElement(
colors.filter(color => color !== colorStart && color !== colorMid)
);
const gradient = ctx.createLinearGradient(0, area.bottom, 0, area.top);
gradient.addColorStop(0, colorStart);
gradient.addColorStop(0.5, colorMid);
gradient.addColorStop(1, colorEnd);
return gradient;
}
export function App() {
const chartRef = useRef<ChartJS>(null);
const [chartData, setChartData] = useState<ChartData<'bar'>>({
datasets: [],
});
useEffect(() => {
const chart = chartRef.current;
if (!chart) {
return;
}
const chartData = {
...data,
datasets: data.datasets.map(dataset => ({
...dataset,
borderColor: createGradient(chart.ctx, chart.chartArea),
})),
};
setChartData(chartData);
}, []);
return <Chart ref={chartRef} type='line' data={chartData} />;
}