reactor
reactor

Reputation: 1941

how to get React chartjs to resize back down with window

I have this code, which, for some reason, will grow when I resize a window, but not shrink. I was wondering how to remedy this.

https://codesandbox.io/s/react-chartjs-2-example-1nur4

import React from "react";
import { render } from "react-dom";
import LineDemo from "./LineDemo";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const App = () => (
  <div style={styles}>
    <table style={{ width: "100vw", borderCollapse: "collapse" }}>
      <tbody>
        {Array.from({ length: 4 }, el => "foo")
          .concat(<LineDemo />)
          .map(el => (
            <td style={{ border: "solid" }}>{el}</td>
          ))}
      </tbody>
    </table>
  </div>
);

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

Upvotes: 10

Views: 14479

Answers (3)

117
117

Reputation: 197

another solution that works, for anyone reading in 2023 is this:

canvas {
  width: 100% !important;
}

Upvotes: 3

Bruno Andrade
Bruno Andrade

Reputation: 456

What worked for me was to add chart container a width style:

<div style={{width: '99%'}}>
    <Bar options={options} data={data} />
</div>

However if I set width 100% it won't work lol

Upvotes: 12

Rounak
Rounak

Reputation: 806

Have a detailed look at https://www.chartjs.org/docs/latest/configuration/responsive.html. The Important Note section mentions how responsiveness can be achieved. It states that

Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size.

In your case, the parent container for the line chart is the <div> element. The render function of LineDemo component in LineDemo.js file then can be modified to look like:

render() {
  return (
    <div style={{ position: "relative", margin: "auto", width: "80vw" }}>
      <h2>Line Example</h2>
      <Line ref="chart" data={data} />
    </div>
  );
}

Here is a working example: https://codesandbox.io/s/react-chartjs-2-example-hzygw

Upvotes: 9

Related Questions