reactjs / react-chartjs

common react charting components using chart.js
MIT License
2.93k stars 301 forks source link

changing a charts width height dynamically does not seem to change anything #73

Closed CurtisHumphrey closed 6 years ago

CurtisHumphrey commented 8 years ago

For example lets have a chart like this:

<Line data={chart_data}  width={width} height='400' redraw />

If I change the width later the line chart does not redraw a new canvas with a new width

eugensunic commented 7 years ago

This is the solution to the problem: First thing: set the react lifecycle in order for things to get dynamic in your canvas wrapper, the code below is easy and understandable.

constructor(props) {
     super(props);
     this.state=({width:800, height:300})
   }
   updateDimensions(){
     console.log("Width is:"+this.state.width);
     console.log("Height is:"+this.state.height);
     let width = this.refs.div.offsetWidth;
     let height= this.refs.div.offsetHeight;
     this.setState({width:width,height:height});
   }
   componentWillMount(){
     this.updateDimensions.bind(this);
   }
   componentDidMount(){
      window.addEventListener("resize", this.updateDimensions.bind(this));
   }

Second thing: make the style for the react chart, so you can attach it to the style attribute aftewards

  const canStyle = {
      width: this.state.width 
    };

Third thing: put the canStyle into the react-chart component, and remember the canvas inner width (800) and the canvas inner height(300) must stay constant! width=800 and height=300 are the best thing for me. You can put your values.

<BarChart style={canStyle} data={your_array} width=800 height=300 redraw/>

Now your Chart adjusts to the screen after resizing the screen. The style ={canStyle} is the key here.