[Chartjs]-How to resize Chart.JS element in React.js?

25πŸ‘

βœ…

The documentation for ChartJS states that you need to set maintainAspectRatio to false for it to use the width and height props that you pass into your chart.

In order for Chart.js to obey the custom size you need to set maintainAspectRatio to false.

<Doughnut
  data={data}
  width={"30%"}
  options={{ maintainAspectRatio: false }}
/>

3πŸ‘

Doing the following works for me:

  1. set height and width on the <Doughnut /> component.
  2. Set the maintainAspectRation to false.

Here is what the outcome looks like:

<Doughnut
  data={data}
  height="200px"
  width="200px"
  options={{ maintainAspectRatio: false }}
/>

3πŸ‘

Wrap it in div Container and set width and height.

Ex:

<div style={{height:"60vh",position:"relative", marginBottom:"1%", padding:"1%"}}>
     <Doughnut options={options} data={chartData} />
</div>

2πŸ‘

"chart.js": "^2.9.3",
"react-chartjs-2": "^2.11.2"

docs: https://www.chartjs.org/docs/2.9.4/general/responsive.html

OPTIONS ARE MOST IMPORTANT:

const options = {
    maintainAspectRatio: false,
    aspectRatio: 1
    }

    <div style={{width: '500px'}}>   
            <Doughnut data={chartData} options={options}  />
    </div>

so now what ever size you put into Parent Div, e.g. 500px, will be the size of the Chart

0πŸ‘

Something that worked for me was to set the width manually using the style property and to add maintainAspectRatio: false to options like so:

<Pie
    style={{ width: "500px" }}
    options={{
      maintainAspectRatio: false}} />

Leave a comment