One of the most frustrating things which each frontend developer faces, is the challenge of scaling graphs library. It very often happens, especially with an older library, that it is not responsive. It just adjusts the size when it is mounted to the DOM and doesn’t scale dynamically when a browser window is resizing.
How can we solve this issue?
Of course the first thing we can do, is to try to replace it with another one. However, in practice, this solution is rarely possible, especially when we are working with legacy software where a mass of other components are already using it. In that case, reworking the code of all components doesn’t make any sense. So what then? Well, fortunately, if you know React you don’t have to worry. In the React world everything is simple, and this case is no different. What we have to do is just force re-render to our component each time the browser windows change size. Thanks to that we will be able to recalculate a new dimension for our object and bring it back with a new, adjusted size.
How to do this? Check code below.
import React, { Component } from 'react';
import LineChart from 'chart-graphs';
export default class Chart extends Component {
constructor() {
super();
this.state = {
width: 800,
height: 182
}
}
/**
* Calculate & Update state of new dimensions
*/
updateDimensions() {
if(window.innerWidth < 500) {
this.setState({ width: 450, height: 102 });
} else {
let update_width = window.innerWidth-100;
let update_height = Math.round(update_width/4.4);
this.setState({ width: update_width, height: update_height });
}
}
/**
* Add event listener
*/
componentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions.bind(this));
}
/**
* Remove event listener
*/
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this));
}
render() {
return(
<div id="lineChart">
<LineChart width={this.state.width} height={this.state.height} />
</div>
);
}
}