Can't change the time of the xAxes in the Chart.js - javascript

So I have ChartData Component. I am taking the data from an API, the data is being displayed through Chart. I have determine Format Logic, which it's the main thing is to determine the time of the data, I have 3 buttons, the thing that I am struggling to achieve is when let's say I wanna see the data of 7days when I press the button. I can see data is changing in the yAxes but I can't see time being changed on thexAxes, it's still set to hours, it should display the days.
ChartData
import React, { useRef, useEffect, useState } from "react";
import 'chartjs-adapter-moment';
import annotationPlugin from 'chartjs-plugin-annotation';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
Chart.register(annotationPlugin);
const determineTimeFormat = (
timeFormat: string,
day: any,
week: any,
year: any
) => {
switch (timeFormat) {
case "24h":
return day;
case "7d":
return week;
case "1y":
return year;
default:
return day;
}
};
interface Props {
data: any
}
const ChartData: React.FC<Props> = ({ data }) => {
const chartCanvasRef = useRef<HTMLCanvasElement | null>(null);
const { day, week, year, detail } = data;
const [timeFormat, setTimeFormat] = useState("24h");
const [isRebuildingCanvas, setIsRebuildingCanvas] = useState(false);
useEffect(() => {
setIsRebuildingCanvas(true);
}, [timeFormat]);
useEffect(() => {
if (isRebuildingCanvas) {
setIsRebuildingCanvas(false);
}
}, [isRebuildingCanvas]);
useEffect(() => {
if (chartCanvasRef && chartCanvasRef.current && detail) {
const chartCanvas = chartCanvasRef.current
if (isRebuildingCanvas || !chartCanvas) {
return;
}
const chartInstance = new Chart(chartCanvasRef.current, {
type: "line",
data: {
datasets: [
{
label: `${detail.name} price`,
data: determineTimeFormat(timeFormat, day, week, year),
backgroundColor: "rgba(134,159,152, 1)",
borderColor: "rgba(174, 305, 194, 0.4",
},
],
},
Options
options: {
plugins: {
annotation: {
annotations: {
}
}
},
animations: {
tension: {
duration: 1000,
easing: 'linear',
from: 1,
to: 0,
loop: true
}
},
maintainAspectRatio: false,
responsive: true,
scales: {
x:
{
type: 'time',
},
},
}
});
return () => {
chartInstance.destroy();
}
}}, [day, isRebuildingCanvas,timeFormat, week, year, detail]);
Rest of the Component
return (
<div className='chart__container'>
{renderPrice()}
{isRebuildingCanvas ? undefined : (
<canvas ref={chartCanvasRef} width={250} height={250} id='myChart'></canvas>
)}
<button className='time__format' onClick={() => setTimeFormat("24h")}>24h</button>
<button className='time__format' onClick={() => setTimeFormat("7d")}>7d</button>
<button className='time__format' onClick={() => setTimeFormat("1y")}>1y</button>
</div>
);
};
export default ChartData;

I have created a similar working example without reactjs. This can be useful for you to understand. You can refer the fiddle as well. A limitation that am currently facing is if there is data more than 100 then am getting errors while updating the data, performed slicing of data upto 100 to make it working.
var coinData = {};
var fetchData = async() => {
api = "https://api.coingecko.com/api/v3";
id = "bitcoin";
var [day1, week1, year1, detail1] = await Promise.all([
fetch(api + `/coins/${id}/market_chart/?vs_currency=usd&days=1`).then(data => {
return data.json()
}),
fetch(api + `/coins/${id}/market_chart/?vs_currency=usd&days=7`).then(data => {
return data.json()
}),
fetch(api + `/coins/${id}/market_chart/?vs_currency=usd&days=365`).then(data => {
return data.json()
}),
fetch(api + `/coins/markets/?vs_currency=usd&ids=${id}`).then(data => {
return data.json()
})
]);
coinData = {
day: formatData(day1.prices).slice(0, 100),
week: formatData(week1.prices).slice(0, 100),
year: formatData(year1.prices).slice(0, 100),
detail: detail1[0]
}
}
const formatData = (data) => {
return data.map((el) => {
return {
t: el[0],
y: el[1].toFixed(2)
};
});
};
const determineTimeFormat = (timeFormat) => {
switch (timeFormat) {
case "24h":
return coinData.day;
case "7d":
return coinData.week;
case "1y":
return coinData.year;
default:
return coinData.day;
}
};
var chartInstance;
fetchData().then(() => {
/* console.log(coinData); */
var ctx = document.getElementById('chartJSContainer');
chartInstance = new Chart(ctx, {
type: "line",
labels: false,
data: {
datasets: [{
label: `${coinData.detail.name} price`,
data: determineTimeFormat('1d'),
parsing: {
yAxisKey: 'y',
xAxisKey: 't',
},
backgroundColor: "rgba(134,159,152, 1)",
borderColor: "rgba(174, 305, 194, 0.4)"
}],
},
options: {
scales: {
x: {
ticks: {
source: "data"
},
type: 'time',
time: {
unit: "day"
}
}
},
}
});
});
function setTimeFormat(format) {
Chart.instances[0].data.datasets[0].data = determineTimeFormat(format);
Chart.instances[0].update();
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.1/dist/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#1.0.0/dist/chartjs-adapter-moment.min.js"></script>
<body>
<button className='time__format' onclick="setTimeFormat( '24h')">24h</button>
<button className='time__format' onclick="setTimeFormat( '7d')">7d</button>
<button className='time__format' onclick="setTimeFormat( '1y')">1y</button><br><br>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

Related

Error when trying to update chart data: 'this undefined'

I am working in Vue. My goal is create dynamic stepsize for timeline chart. Here my
TimelineChart.vue:
<template>
<div class="chart chart-timeline">
<ChartLegend
:items="legend"
:allowFilterCreation="allowFilterCreation"
#highlight="highlighted = $event"
#toggle="toggleDatasetVisibility($event)"
#apply-filter="$emit('apply-filter', $event)"
v-if="legend"/>
<div class="chart-container" v-show="hasData">
<canvas ref="chart"></canvas>
<hr> <hr> <hr> Stepsize Y
<input type="number" id ="ySteps">
<hr> Stepsize X
<input type="number" id ="xSteps">
</div>
<h2 class="subtitle is-5" v-if="!hasData">
No data
</h2>
</div>
</template>
<script>
import _ from "lodash";
import Chart from "chart.js";
import Moment from "moment";
import ChartLegend from "#/components/charts/ChartLegend";
import ChartMixin from "#/components/charts/ChartMixin";
import Deferred from "#/Deferred";
export default {
props: ["data", "multiMode", "labelConverter", "valueConverter", "allowFilterCreation"],
components: { ChartLegend },
mixins: [ChartMixin],
data() {
return {
chart: Deferred.create(),
highlighted: null
};
},
computed: {
timeline() {
return this.data ? _.map(this.data.parameter, it => new Moment(it)) : [];
},
keys() {
return this.data ? _.map(this.data.datasets, it => it.name) : [];
},
labels() {
const converter = this.labelConverter || _.identity;
return _.map(this.keys, converter);
},
datasets() {
return this.data ? _.map(this.data.datasets, it => it.data) : [];
},
datasetCount() {
return this.datasets.length;
},
legend() {
if (!this.multiMode) {
return null;
}
return _.zipWith(this.keys, this.labels, this.palette, (key, text, color) => ({
id: key,
text,
color: color.normal,
hidden: _.includes(this.hiddenDatasets, key)
}));
},
chartColors() {
const highlightIndex = this.highlighted !== null && !_.includes(this.hiddenDatasets, this.highlighted)
? _.indexOf(this.keys, this.highlighted)
: null;
const colors = [];
for (const index of _.keys(this.datasets)) {
const color = this.palette[index];
if (highlightIndex !== null) {
if (index == highlightIndex) {
colors.push({ backgroundColor: color.strongMuted, borderColor: color.strong });
} else {
colors.push({ backgroundColor: color.weakMuted, borderColor: color.weak });
}
} else {
colors.push({ backgroundColor: color.normalMuted, borderColor: color.normal });
}
}
return colors;
}
},
mounted() {
this.chart.resolve(new Chart(this.$refs.chart, {
type: "line",
data: {
datasets: [],
labels: []
},
options: {
maintainAspectRatio: false,
legend: { display: false },
scales: {
xAxes: [{
type: "time",
time: {
isoWeekday: true,
displayFormats: {
hour: "HH:mm",
day: "DD-MM",
week: "DD-MM",
month: "MM-YYYY"
}
},
tooltips: {
},
ticks: { source: "labels",
// stepSize: 2
}
}],
yAxes: [{
ticks: { min: 0, precision: 0,
stepSize: 1
}
}]
},
spanGaps: false,
tooltips: {
callbacks: {
label: item => {
const converter = this.valueConverter || _.identity;
const label = this.multiMode ? (this.labels[item.datasetIndex] + ": ") : "";
return label + converter(this.datasets[item.datasetIndex][item.index]);
}
}
}
}
}));
// method that change stepsize
const ySteps = document.getElementById('ySteps');
ySteps.addEventListener('input', (e) => {
// eslint-disable-next-line no-undef
stepSize(this.$refs.chart, e)
});
function stepSize(chart) {
this.chart.resolve.scales.yAxes.stepSize = ySteps.value;
this.$refs.chart.update()
}
watch: {
data() {
this.resetDatasetVisibility();
}
}
}
</script>
When I alter stepsize nothing happen. In debug mode I have noticed the following pattern:
When I create chart 'this.chart' is not undefined. But when I use function stepSize I have an error, that this.chart is undefined. I have read a documentation about it, but I still do not understand how to connect to instance and change the property in the chart.
this.chart inside stepSize function will not be referring to the chart object inside your data node, because stepSize is not a vue compoenent method, its a javascript function. So this wont be refering to your vue scope.
Since you are already passing your chart object as a parameter to stepSize function as stepSize(this.$refs.chart, e), you can make use of the same inside your stepSize function like
function stepSize(chart) {
chart.resolve.scales.yAxes.stepSize = ySteps.value;
chart.update();
}

how to map time with its respective data in chart

I'm working on apexcharts. I managed to pass data in chart, but there seem to be issue with timestamps. I have two data i.e sender and receiver, each has its own timestamps. the graph's x-axis is based on the timestamps. but I don't know how to map the timestamp with its respective data. currently, the data in the graph are not showing right due to the timestamp issue. kindly help me to fix it. thanks in advance
here's my full code
const receiverData = [];
const senderData = [];
const timeData = [];
export default function GraphCard() {
const [GraphData, setGraphData] = useState([])
const showData = () => {
axios.get('http://localhost:8006/api/v2/user/transactions').then(function (res) {
var result = res.data.data;
console.log(result)
if (result.data) {
setGraphData(result.data)
for (const obj of result.data) {
if (obj.role === 'Sender') {
receiverData.push(obj.tokens)
timeData.push(obj.date)
}
if (obj.role === 'Receiver') {
senderData.push(obj.tokens)
timeData.push(obj.date)
}
}
console.log("Reciever", receiverData)
console.log("Sender", senderData)
}
else {
console.log('error')
}
})
}
const state = {
series: [{
color: '#000073',
name: 'Received',
data: receiverData.map((data) => (data))
},
{
color: '#CA9026',
name: 'Sent',
data: senderData.map((data) => (data))
}],
options: {
chart: {
height: 280,
type: 'area'
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
xaxis: {
type: 'datetime',
categories: timeData.map((data) =>(data))
},
yaxis: {
type: ''
},
tooltip: {
x: {
format: 'dd/MM/yy HH:mm'
},
},
},
}
useEffect(() => {
showData()
}, [])
return (
<Card >
<CardContent display='flex' sx={{ flexDirection: 'column', }} >
<Stack flexDirection='row' alignItems="center" gap={1}>
< SsidChartOutlinedIcon sx={{ color: "text.secondary" }} />
<Typography sx={{ fontSize: 15, fontWeight: 'bold' }} color="text.secondary" gutterBottom>
Recent Transactions
</Typography>
</Stack>
<div id="chart">
<ReactApexChart options={state.options} series={state.series} type="area" height={280} />
</div>
</CardContent>
</Card>
);
}
On apex chart website, they have a case that is similar to yours:
series: [{
data: [{ x: '05/06/2014', y: 54 }, { x: '05/08/2014', y: 17 } , ... , { x: '05/28/2014', y: 26 }]
}]
apexchart docs
To achieve this kind of objects, you can just do this:
const showData = () => {
axios.get('http://localhost:8006/api/v2/user/transactions').then(function (res) {
var result = res.data.data;
console.log(result)
if (result.data) {
setGraphData(result.data)
for (const obj of result.data) {
if (obj.role === 'Sender') {
receiverData.push({x: obj.date.toString(), y: obj.tokens}) //date.toString() is not necessary if your date is already a string
timeData.push(obj.date)
}
if (obj.role === 'Receiver') {
senderData.push({x: obj.date.toString(), y: obj.tokens})
timeData.push(obj.date)
}
}
console.log("Reciever", receiverData)
console.log("Sender", senderData)
}
else {
console.log('error')
}
})
}
And the rest should not need to be changed.

project become whole blank during import graph. Linegraph problem in Reactjs

//* This is Linegraph.js file /
import React, { useEffect, useState } from 'react'
import { Line } from 'react-chartjs-2'
import numeral from 'numeral'
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 0,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,0");
},
},
},
scales: {
xAxes: [
{
type: "time",
time: {
format: "MM/DD/YY",
tooltipFormat: "ll",
},
},
],
yAxes: [
{
gridLines: {
display: false,
},
ticks: {
callback: function (value, index, values) {
return numeral(value).format("0a");
},
},
},
],
},
};
const LineGraph = ({ casesType="cases" }) => {
const [data, setData] = useState({})
const buildChartData = (data, caseType) => {
const chartData = []
let lastPoint;
for(let date in data.cases){
if(lastPoint) {
const newPoint = {
x: date,
y: data[caseType][date] - lastPoint
}
chartData.push(newPoint)
}
lastPoint = data[caseType][date]
}
return chartData
}
useEffect(() => {
const fetchData = async () => {
fetch('https://disease.sh/v3/covid-19/historical/all?lastdays=120')
.then(response => response.json())
.then(data => {
console.log(data)
const chartData = buildChartData(data, casesType)
setData(chartData)
})
}
fetchData()
}, [casesType])
return (
<div>
{data?.length > 0 && (
<Line
options={options}
data={{
datasets: [{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data
}]
}}
/>
)}
</div>
)
}
export default LineGraph

API Data to be displayed in Line Charts (react-chartjs-2)

I'm trying to figure out how to accurately use and display this API values in a line chart.
API Call with Line Chart:
import React, { Component } from 'react'
import { Line } from 'react-chartjs-2'
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXX_XXX_XXXXXXX',
'Content-Type': 'application/json'
};
class TotalLineChart extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"where": "{40.CT. 'In Progress'}","sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response.json())
.then( data => this.setState({ data })
);
}
render() {
const data = {
labels: ['50', '100', '150', '200', '250', '300'],
datasets: [
{
label: 'TOTAL',
data: [
{x: this.state.data["6"].value, y: this.state.data["3"].value },
],
fill: false,
borderColor: '#00498D'
},
],
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
return (
<div>
<Line data={data} options={options} />
</div>
)
}
}
export default TotalLineChart;
Example of API working rendering data:
import React, { Component } from 'react'
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXX_XXXX_XXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class JobsTableApi extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"where": "{40.CT. 'In Progress'}","sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response.json())
.then( data => this.setState({ data })
);
}
render() {
const { data } = this.state;
if (data === null) return 'Loading Job Data... ';
return (
<div>
{Object.keys(data["data"]).map(item => (
<div key = {item}>
{data["data"][item][6].value}
</div>
))}
</div>
)
}
}
export default JobsTableApi;
My Idea is that I have multiple line charts and all the data from the API, I'm attempting to display this data on line charts and have them change when the Title changes automatically so it just Cycles through the whole job show the Title and job info.
Any Ideas on what I'm doing wrong?
Struggling on this, I don't know how to get each ID in the API body to be able to be used in the line chart...
API Response Sample:
{
"data": [
{
"3": {
"value": 177
},
"6": {
"value": "2220 Three Kings "
},
"40": {
"value": "In Progress"
},
"80": {
"value": 41406.07
},
"81": {
"value": 42076.44499999999
},
"82": {
"value": 1384.888156072408
},
UPDATE
This is what I'm trying to figure out how to do... but obviously doesn't work and can't figure out the assigning the ids to fields to actually display in the line chart.
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
const TotalLineChart = () => {
const [chartData, setChartData] = useState({});
// const [designHours, setdesignHours] = useState([]);
// const [designAmount, setdesignAmount] = useState([]);
// const [subRoughHours, setSubRoughHours] = useState([]);
// const [subRoughAmount, setSubRoughAmount] = useState([]);
// const [roughHours, setRoughHours] = useState([]);
// const [roughAmount, setRoughAmount] = useState([]);
// const [finishHours, setFinishHours] = useState([]);
// const [finishAmount, setFinishAmount] = useState([]);
// const [closeHours, setCloseHours] = useState([]);
// const [closeAmount, setCloseAmount] = useState([]);
// const [actualHours, setActualHours] = useState([]);
// const [actualAmount, setActualAmount] = useState([]);
const chart = () => {
let designHours = [];
let designAmount = [];
let subRoughHours = [];
let subRoughAmount = [];
let roughHours = [];
let roughAmount = [];
let finishHours = [];
let finishAmount = [];
let closeHours = [];
let closeAmount = [];
let actualHours = [];
let actualAmount = [];
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXX_XXXX_XXXXXXXXXXX',
'Content-Type': 'application/json'
};
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"where": "{40.CT. 'In Progress'}","sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response.json())
.then(res => {
console.log(res);
for (const dataObj of res.data.data) {
designHours.push(parseInt(dataObj.value, 88));
designAmount.push(parseInt(dataObj.value, 91));
subRoughHours.push(parseInt(dataObj.value, 92));
subRoughAmount.push(parseInt(dataObj.value, 95));
roughHours.push(parseInt(dataObj.value, 96));
roughAmount.push(parseInt(dataObj.value, 98));
finishHours.push(parseInt(dataObj.value, 104));
finishAmount.push(parseInt(dataObj.value, 107));
closeHours.push(parseInt(dataObj.value, 477));
closeAmount.push(parseInt(dataObj.value, 480));
actualHours.push(parseInt(dataObj.value, 479));
actualAmount.push(parseInt(dataObj.value, 224));
}
setChartData({
type: 'scatter',
data: {
datasets: [
{
data: [
{x: designHours, y: designAmount },
{x: subRoughHours, y: subRoughAmount },
{x: roughHours, y: roughAmount },
{x: finishHours, y: finishAmount },
{x: closeHours, y: closeAmount }
],
backgroundColor: ["rgba(75, 192, 192, 0.6)"],
borderWidth: 4
}
]
}
});
})
.catch(err => {
console.log(err);
});
console.log(designHours, designAmount, subRoughHours, subRoughAmount, finishHours, finishAmount, closeHours, closeAmount, actualHours, actualAmount);
};
useEffect(() => {
chart();
}, []);
return (
<div className="App">
<div>
<Line
data={chartData}
options={{
responsive: true,
title: { text: "", display: true },
scales: {
yAxes: [
{
ticks: {
autoSkip: true,
maxTicksLimit: 10,
beginAtZero: true
},
gridLines: {
display: true
}
}
],
xAxes: [
{
gridLines: {
display: true
}
}
]
}
}}
/>
</div>
</div>
);
};
export default TotalLineChart;
That way I can select each field I need and display it in the line chart...
Any suggestions or ideas?

how to resolve the problem that hovering mouse on chart will appear old data/charts?

I used react hooks useEffect for rendering a chart from chart.js to canvas. However, I found problem of old chart showing when I hover my mouse on the chart. From the sources I found online I realized the problem might be able to solve by chart.destroy(), but I just do not know where and how to use it in my case of code. I have attached a snip of my code here, hope anybody can help me out.
import React, { useEffect } from 'react';
import Chart from 'chart.js';
import { Card } from 'components/Card';
import { localDateTime, dateFilter } from 'helpers';
const red = '#644DFF';
const purple = '#F73F64';
const DailyTrafficCard = (props) => {
const { store, capacity, data, setVar} = props;
const lastSevenDays = Array(7)
.fill()
.map((_, i) => {
const localdate = localDateTime(store);
return localdate()
.subtract(i, 'day')
.format('YYYY-MM-DD[T]07:00:00[Z]');
});
useEffect(() => {
const ctx = document && document.querySelector('#daily-traffic-chart');
if (!ctx) {
return;
}
const bar = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: data[data.length-1],
barThickness: 13,
backgroundColor: (ctx) => {
const idx = ctx && ctx.dataIndex;
const val = ctx && ctx.dataset && ctx.dataset.data && ctx.dataset.data[idx];
return val < 40 ? purple : red;
}
}]
},
options: {
intersect: false,
legend: {
display: false,
},
scales: {
xAxes: [{
type: 'time',
offset: true,
time: {
unit: 'hour',
displayFormats: {
hour: 'HH',
},
},
ticks: {},
gridLines: {
display: false,
},
}],
yAxes: [{
gridLines: {
display: true,
},
ticks: {
beginAtZero: true,
min: 0,
max: capacity,
stepSize: 5
},
}],
},
}
});
}, [data,capacity]);
const handleOnChange = (event) => {
setVar(event.target.value);
}
return (
<Card
classname="DailyTrafficCard"
icon={<span><i className="icon-user"/></span>}
title={<h3>Daily Traffic Analytics</h3>}>
<div className="daily">
<div className="daily-head p-4 text-center">
<select className="py-2 px-3" onChange={handleOnChange}>
{lastSevenDays.map(date => (
<option key={date} value={date}>{dateFilter(date, 'dddd')}</option>
))}
</select>
</div>
<div className="px-8">
{data && data.length > 0 && (
<canvas width="250" id="daily-traffic-chart"></canvas>
)}
</div>
</div>
</Card>
)
}
export {
DailyTrafficCard
}

Categories

Resources