[Chartjs]-Can't resize react-chartjs-2 doughnut chart

14👍

Have a look in the chartjs docs under responsive.

In the options, set responsive: true, maintainAspectRatio: true and remove width and height.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import { Doughnut } from 'react-chartjs-2'

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      data: {
        datasets: [{
          data: [10, 20, 30]
        }],
        labels: [
          'Red',
          'Yellow',
          'Blue'
        ]
      }
    }
  }

  render() {
    return (

      <Doughnut
        data={this.state.data}
        options={{
          responsive: true,
          maintainAspectRatio: true,
        }}
      />
    )
  }
}

render(<App />, document.getElementById('root'));

Here is a working StackBlitz

5👍

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import { Doughnut } from 'react-chartjs-2'

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      data: {
        datasets: [{
          data: [10, 20, 30]
        }],
        labels: [
          'Red',
          'Yellow',
          'Blue'
        ]
      }
    }
  }

  render() {
    return (

      <Doughnut
        data={this.state.data}
        options={{
          responsive: true,
          maintainAspectRatio: false,
        }}
      />
    )
  }
}

render(<App />, document.getElementById('root'));

0👍

This answer is same as above two answers except an extra div in the render, see below

render() {
    return (
     <div style={{width: '10%', height: '10%'}}>
      <Doughnut
        data={this.state.data}
        options={{
          responsive: true,
          maintainAspectRatio: true,
        }}
      />
     </div>
    )
  }

Since we set the maintainAspectRatio to true, we can’t set the height, width to graph itself rather we can set the height, width to its parent div which allow us to modify the dimensions easily.

Happy Coding…

Leave a comment