Skip to content

Instantly share code, notes, and snippets.

@SmartWeb25
Last active October 12, 2021 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SmartWeb25/63230ed0c96ebe0215d35a0555b4ee83 to your computer and use it in GitHub Desktop.
Save SmartWeb25/63230ed0c96ebe0215d35a0555b4ee83 to your computer and use it in GitHub Desktop.
react-chartjs-2 horizontall scrollable with fixed y-axis
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
export default class ChartComponent extends Component {
getOptions = () => {
var itself = this;
return {
maintainAspectRatio: false,
responsive: true,
elements: {
line: {
fill: false
}
},
scales: {
'x-axis-1' : {
display: true,
grid: {
display: false,
},
ticks:{
display: true,
}
},
'y-axis-1' : {
display: true,
grid: {
display: true,
},
ticks:{
display: true,
}
}
},
plugins: {
tooltip: {
mode: 'point',
callbacks: {
afterLabel: (context) => {
// some customization here
}
}
},
legend: {
display: this.props.showLegend ? this.props.showLegend : false,
position: 'top',
labels: {
usePointStyle: true,
}
},
},
"animation": {
"duration": 1,
"onComplete": function() {
var scale = window.devicePixelRatio;
var sourceCanvas = this.ctx.canvas;
var copyWidth = this.scales['y-axis-1'].width - 7;
var copyHeight = this.scales['x-axis-1'].top + 10;
if (itself.refs.ticksWrp && (copyWidth > 0) && (copyHeight > 0)) {
var targetCtx = itself.refs.ticksWrp.getContext("2d");
if (targetCtx && sourceCanvas) {
targetCtx.scale(scale, scale);
targetCtx.canvas.width = copyWidth * scale;
targetCtx.canvas.height = copyHeight * scale;
targetCtx.canvas.style.width = `${copyWidth}px`;
targetCtx.canvas.style.height = `${copyHeight}px`;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth * scale, copyHeight * scale, 0, 0, copyWidth * scale, copyHeight * scale);
if (itself.refs.chartWrp)
itself.refs.chartWrp.scrollLeft = itself.refs.chartWrp.scrollWidth; // scroll to the right
}
}
}
}
};
}
render() {
let { data } = this.props;
var options = this.getOptions();
var width = data.datasets[0].data.length < 7 ? '100%' : (data.datasets[0].data.length*50).toString() + 'px';
var height = mode === 'monthly' ? '200px' : '300px';
return (<div className="chart-wrp">
<div className="chart-overflow-wrp" ref="chartWrp">
<div className="main-chart-wrp" style={{width: width}}>
<Line data={data} options={options} height={height}/>
</div>
</div>
<canvas ref="ticksWrp" className="custom-y-ticks" height={height} width="0"></canvas>
</div>);
}
}
.chart-wrp {
position: relative;
.chart-overflow-wrp {
width: 100%;
overflow-x: auto;
overflow-y: hidden;
}
.custom-y-ticks {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
background-color: #fff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment