How to route to a page on click event in apex charts? - reactjs

A beginner in react... I am able to reach a function post-click event of a bar but unable to route to a link or page.
I may have other defined routes to which I want to go, like a page consisting of a table, listing all the sales and it automatically gets filtered. How am I supposed to do that? Please guide me through. I have searched for this a lot and finally was able to reach a function but now I am stuck.
class SalesWidget2 extends Component {
routeChange(index){
console.log('I am here');
// let history = useHistory();
// history.push('google.com');
}
constructor(props) {
super(props);
this.state = {
colors:['#FEB019'],
series: [{
name: 'Sales ',
type: 'column',
data: [1.4, 2, 2.5, 1.5, 2.5, 2.8, 3.8, 4.6],
}],
options: {
chart: {
type: 'bar',
height: 350,
fontFamily: 'Roboto, sans-serif',
fontSize: '14px',
events:{
click: (event, chartContext, config) =>{
this.routeChange(config.dataPointIndex);
}
},
},
plotOptions: {
bar: {
borderRadius: 4,
horizontal: false,
}
},
dataLabels: {
enabled: false
},
title: {
text: 'My Store Performance',
align: 'left',
offsetX: 50,
fontSize: '14px',
},
xaxis: {
title: {
text: 'Time',
style: {
fontSize: '14px',
},
},
categories: ['June 2021', 'July 2021','August 2021', 'September 2021', 'October 2021','November 2021','December 2021', 'January 2022'],
},
yaxis:{
title: {
text: 'Sales',
style: {
fontSize: '14px',
}
},
labels:{
formatter: function(val) {
return val.toFixed(1);
}
}
},
tooltip: {
x:{
title:{
text: 'Sales',
}
},
y: {
formatter: function(val) {
return "$" + val.toFixed(0) + " million";
}
}
},
fill:{
colors:['#FEB019'],
},
stroke:{
colors:['#FEB019'],
},
legend: {
horizontalAlign: 'left',
offsetX: 40,
fontSize: '14px',
},
responsive: [{
breakpoint: 1000,
options: {
plotOptions: {
bar: {
horizontal:true,
vertical: false,
}
},
legend:{
position: "bottom"
},
yaxis:{
labels:{
formatter: function(val) {
return val.toFixed(0);
}
}
},
xaxis:{
labels:{
formatter: function(val) {
return val.toFixed(1);
}
}
},
},
}],
},
};
}
render() {
return(
<Chart options={this.state.options} series={this.state.series} type="bar" height="350" />
)
}}

Related

How to make a realtime chart with Highcharts, Firebase, ReactJS with Typescript?

I need to create a graph in real time getting data from Firebase. I'm using ReactJs with typescript along with Highcharts.
I've already managed to simulate Highcharts in real time, but now I'm wondering how I can connect it to get the data that will be added to Firebase.
Global Graph Component:
import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import HighchartsMore from 'highcharts/highcharts-more';
import HighchartsAccessibility from 'highcharts/modules/accessibility';
import HighchartsData from 'highcharts/modules/data';
import HighchartsExporting from 'highcharts/modules/exporting';
import HighchartsHeatmap from 'highcharts/modules/heatmap';
import HighchartsTreeChart from 'highcharts/modules/treemap';
import { defaultTheme } from '../../../styles/themes';
HighchartsAccessibility(Highcharts);
HighchartsMore(Highcharts);
HighchartsData(Highcharts);
HighchartsHeatmap(Highcharts);
HighchartsTreeChart(Highcharts);
HighchartsExporting(Highcharts);
interface IChartProps {
options: Highcharts.Options;
}
export const labelsStyle = (
fontSize = 20,
color = defaultTheme.palette.grey[900]
) => ({
color,
fontSize: `${fontSize / 16}rem`,
fontFamily: 'Poppins',
margin: '0px',
fontWeight: 400,
lineHeight: `${(fontSize + 10) / 16}rem`,
});
export const Chart: React.FC<IChartProps> = ({ options }) => {
Highcharts.setOptions({
// rangeSelector: {
// enabled: false,
// },
// navigator: {
// enabled: false,
// },
xAxis: {
labels: {
style: labelsStyle(),
},
},
yAxis: {
labels: {
style: labelsStyle(18, defaultTheme.palette.grey[200]),
},
},
credits: {
enabled: false,
},
exporting: {
enabled: false,
},
});
return <HighchartsReact highcharts={Highcharts} options={options} />;
};
Realtime Graph Component:
import { TooltipFormatterContextObject } from 'highcharts';
import {
Chart,
labelsStyle,
} from '../../../../shared/components/DataDisplay/Chart';
import { defaultTheme } from '../../../../shared/styles/themes';
import { formatDate } from '../../../../shared/utils/date';
import { getRandomIntInclusive } from '../../../../shared/utils/math';
export const GraphHeartRateMonitor: React.FC = () => {
const analyticsDataState = {
dates: [],
data: [],
};
const options: Highcharts.Options = {
chart: {
borderWidth: 0,
height: '176px',
plotBackgroundColor: defaultTheme.palette.background.default,
type: 'line',
marginRight: 10,
events: {
load() {
const series = this.series[0];
setInterval(function () {
const x = new Date().getTime(), // current time
y = getRandomIntInclusive(80, 120);
series.addPoint([x, y], true, true);
}, 1000);
},
},
},
title: {
text: '',
},
xAxis: {
type: 'datetime',
tickPixelInterval: 300,
labels: {
enabled: false,
},
},
yAxis: {
title: {
text: '',
},
gridLineColor: defaultTheme.palette.background.default,
tickInterval: 10,
labels: {
enabled: false,
},
plotLines: [
{
value: 120,
color: defaultTheme.palette.red[300],
width: 2,
label: {
text: '120',
useHTML: true,
verticalAlign: 'middle',
align: 'left',
style: {
background: defaultTheme.palette.red[300],
borderRadius: '24px',
height: '18px',
padding: '2px 12px',
color: defaultTheme.palette.common.white,
fontFamily: 'Roboto Mono',
fontSize: '12px',
fontWeight: '400',
},
},
},
],
// lineColor: defaultTheme.palette.background.default,
},
legend: {
enabled: false,
},
exporting: {
enabled: false,
},
series: [
{
name: 'Random data',
color: defaultTheme.palette.grey[900],
data: (function () {
// generate an array of random data
let data = [],
time = new Date().getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: getRandomIntInclusive(80, 120),
});
}
return data;
})(),
},
],
tooltip: {
useHTML: true,
backgroundColor: defaultTheme.palette.background.paper,
borderRadius: 4,
shadow: {
color: defaultTheme.palette.common.black,
},
padding: 12,
style: labelsStyle(20, defaultTheme.palette.grey[300]),
formatter() {
const self: TooltipFormatterContextObject = this;
return `
<span> Time:</span>
<strong>${formatDate(new Date(self.x), 'HH:mm:ss')}</strong>
</br>
<span>Heart Rate:</span>
<strong >${self.y} bpm</strong>
`;
},
},
};
return <Chart options={options} />;
};
To call the component just call as a normal component <GraphHeartRateMonitor /> .

Chart.js doughnut text visibility

Chart.js doughnut text visibility. Tell me how to make it so that when the values intersect, the text comes out and changes its position.
const myChart = new Chart(canvas,
{
type: 'doughnut',
data: {
labels: dataNameDB,
datasets: [{
data: dataCountDB,
backgroundColor: backgroundColor,
borderWidth: 0,
}],
},
plugins: [ChartDataLabels, DoughnutLabel],
options: {
cutout: 340,
responsive: true,
animation: false,
plugins: {
legend: {
display: false,
},
datalabels: {
formatter: (val, ctx) => {
return Math.round((ctx.chart.data.datasets[0].data[ctx.dataIndex] * 100) / summChart()) + "%";
},
display: (val,ctx) =>{
return 'auto';
},
clamp: true,
clip: true,
anchor: 'center',
align: 'center',
offset: 1,
font: {
size: 65,
weight: 'bold',
color: '000000'
},
color: '000000',
labels: {
value: {
color: '#000000'
}
}
},
doughnutlabel: {
labels: [{
text: summChart,
font: {
size: 140,
weight: 'bold',
color: '000000'
}
}]
}
}
}
},
);
Now it outputs something like this, but I need it to be like this:
Although the documentation says that display 'auto' is responsible for this, how to catch it when the text is hidden in order to move it?

React HighCharts Custom Legend

I'm trying to customise my chart's legend. My current legend needs to look like this legend.
Basically I need to make the circular icons rectangular and change the legend text color to correspond with the icon.
I've looked everywhere in the docs but I'm not finding a solution. This is how I configured the graph below (legend > itemStyle):
useEffect(() => {
Highcharts.chart(chart.current, {
chart: {
type: 'column',
style: {
fontFamily: '"Roboto", sans-serif',
},
height: 312,
},
credits: {
enabled: false,
},
title: {
text: null,
},
xAxis: {
categories,
labels: {
step: 1,
style: {
fontSize: '8px',
color: '#808992',
},
useHTML: true,
formatter() {
const day = this.value.format('D');
if (moment().isSame(this.value, 'd')) {
return `<strong style="font-weight: 900; color: #0E2C47;">${day}</strong>`;
}
return day;
},
},
gridLineWidth: 1,
},
yAxis: {
min: 0,
title: {
text: `Collections ${showValue ? 'value' : 'count'}`,
style: {
color: '#0E2C47',
fontWeight: '500',
fontSize: '12px',
letterSpacing: '0.3px',
lineHeight: '14.4px',
},
},
labels: {
style: {
fontSize: '8px',
color: '#808992',
},
useHTML: true,
formatter() {
// eslint-disable-next-line react/no-this-in-sfc
const collection = this.value;
const format = Math.abs(collection) > 999 ? `${Math.sign(collection) * ((Math.abs(collection) / 1000).toFixed(1))}K` : Math.sign(collection) * Math.abs(collection);
return `${format}`;
},
},
useHTML: true,
},
legend: {
title: {
text: 'Status',
style: {
fontSize: '12px',
letterSpacing: '0.3px',
color: '#0A1944',
fontWeight: '500',
},
},
itemStyle: {
fontSize: '10px',
letterSpacing: '0.25px',
fontWeight: '500',
color: '#0A1944',
},
reversed: 'true',
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom',
itemMarginBottom: 8,
x: -30,
y: -2,
},
plotOptions: {
series: {
stacking: 'normal',
},
},
tooltip: {
formatter() {
// eslint-disable-next-line react/no-this-in-sfc
return `<b>${this.y} ${this.series.name}</b><br/>${this.x.format('D MMM YYYY')}`;
},
},
series: [{
name: 'Draft',
data: chartData.draft, // [...times(() => null, 30), ...times(random, 31)],
color: collectionStateColors.draft, // processed
legendIndex: 0,
}, {
name: 'Approved',
data: chartData.approved,
color: collectionStateColors.approved, // orange
legendIndex: 1,
}, {
name: 'Expired',
data: chartData.expired,
color: collectionStateColors.expired, // purple
legendIndex: 2,
}, {
name: 'Submitted',
data: chartData.submitted,
color: collectionStateColors.submitted, // purple
legendIndex: 3,
}, {
name: 'Tracking',
data: chartData.tracking,
color: collectionStateColors.tracking, // light blue
legendIndex: 4,
}, {
name: 'Processed',
data: chartData.processed,
color: collectionStateColors.processed, // dark blue
legendIndex: 5,
}],
});
});

Highchart: Break y-axis doest work in react app but is working in js fiddle

using same options in js-fiddle and react app y-axis break is not working in react app but is working fine in js-fiddle.
highchart version i am using is 7.2.1
[enter link description here][1] jsfiddle where break is working
Highcharts.chart('container', {
chart: {
height: 250,
animation: false,
borderColor: '#EFF3F5',
plotBorderColor: '#EFF3F5',
plotBorderWidth: 1,
style: {
},
marginLeft: undefined,
},
legend: {
enabled: false,
},
credits: {
enabled: false,
},
title: {
text: '',
},
subtitle: {
text: '',
},
xAxis: [{
categories: [],
type: 'datetime',
crosshair: {
color: '#96abb6',
width: 1,
snap: false,
},
labels: {
style: {
fontSize: '10px',
color: '#334252',
fontFamily: 'DecimaMono',
textTransform: 'uppercase',
lineHeight: '12px',
whiteSpace: 'nowrap',
},
formatter: function() {
return this.value;
},
},
alternateGridColor: '#F7F9FA',
}, ],
yAxis: [{
tickPositioner: function() {
const positions = [];
let tick = Math.floor(this.dataMin);
const max = Math.min(200, this.dataMax);
const increment = Math.ceil((max - this.dataMin) / 6);
if (this.dataMax !== null && this.dataMin !== null) {
for (tick; tick - increment <= max; tick += increment) {
positions.push(tick);
}
}
if (this.dataMax > 200) {
positions.push(this.dataMax);
}
return positions;
},
title: {
text: null,
},
labels: {
style: {
fontSize: '10px',
textAlign: 'right',
},
},
breaks: [{
from: 200,
to: 1700,
}],
}, ],
series: [{
name: 'Attraction 1',
data: [-0.3543, 5.4184, -31.3792, 95.2435, 135.5852, 104.7914, 84.5844, 8.5129, -38.4724, -54.1816, -13.1134, 677.986, 1763, 1420.0503, 760.9013, 100.8341, 10.4576, 89.8975, 97.4758, 55.4993, 51.4611, 24.1278, 9.9771, 26.9394, 22.042, 32.9894, 145.3526, 88.1315, 135.0617, 119.6472, 29.8568, 43.94, 26.4247, 43.4719, 128.6346, 119.7356, 33.2159, 58.6534, -7.6348, 2.1865, 31.7992],
color: '#e63c45',
lineWidth: 3,
}, ]
});
[enter image description here][2]
[2]: https://i.stack.imgur.com/TIKkO.png screenshot from react app
I reproduce your code in the React environment and everything looks fine, same as in the jsFiddle.
Demo: https://codesandbox.io/s/highcharts-react-demo-83jnr?file=/demo.jsx

React Highstock Won't Work But Highchart works

I would like to switch from React Highcharts to React Highstock because of the compare option I would like to use in Highstock. Here is my config:
var config = {
credits: {
enabled: false
},
title: {
text: '' // No Title
},
chart: {
height: 200,
type: 'line',
backgroundColor: 'rgba(155, 255, 255, 0.0)' // Always transparent Background
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
yAxis: {
labels: {
format: '$ {value}' // Always Money
},
title: {
text: '' // No Label
}
},
xAxis: {
type: 'datetime',
labels: {
format: '{value:%Y\'%b}'
},
tickInterval: getTickInterval(this.props.interval),
},
plotOptions: {
series: {
color: transformColor(this.props.color),
lineWidth: 1,
compare: 'percent',
showInNavigator: true
},
line: {
marker: {
enabled: false
}
}
},
legend: {
layout:'vertical',
align: getLegendPosition(this.props.legend).align,
verticalAlign: getLegendPosition(this.props.legend).verticalAlign,
x: getLegendPosition(this.props.legend).x,
y: getLegendPosition(this.props.legend).y,
floating: true,
itemStyle: {
font: 'sans-serif',
fontWeight: 'bold',
fontSize: '9px'
},
symbolHeight: 10,
symbolWidth: 10
},
series: this.props.series
};
return (
<div>
<ReactHighcharts config={config}/>
</div>
)
}
But when I switch to Highstock:
return (
<div>
<ReactHighstock config={config}/>
</div>
)
It gives me an error:
InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/Highstock.a88db6d5.jsx') is not a valid name.
Any ideas?
Nevermind, don't actually use the React-Highstock npm package. Just do this:
const ReactHighstock = require('react-highcharts/ReactHighstock');

Resources