10

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"));

3 Answers 3

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

i created an account just to let you know this answer resolved about 3 hours of trial. nothing else seemed to work. thank you. ive been googling nonstop, asked chat gpt. nothing did it. but this did
9

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

1 Comment

For future devs, that documentation page moved here: chartjs.org/docs/latest/configuration/responsive.html
3

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

canvas {
  width: 100% !important;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.