Reputation: 261
I am using react-chartjs-2 in a project of mine and I cannot find the problem of the chart, because on mobile all the labels and legend are still big af. I tried responsive: true
, maintainAspectRation: true
. Nothing works
Upvotes: 7
Views: 20244
Reputation: 1936
You can force to re-render your widget on window resize. Here i use the useWindowSize
hook from react-use
export function App() {
useWindowSize();
...
return <Bar key={Date.now} options={options} data={data} />;
}
Upvotes: -1
Reputation: 59
I also had the same problem on my nextjs app. My Bar Chart was not rendering properly on mobile viewport.
I perused the main ChartJS docs on responsiveness and there's a part they talk about resizing the chart canvas when its container resizes. In my case, the container is just a div. Hence In order to fix the issue on mobile viewport, I set my div to be relatively positioned and also set view width and height but it messes up chartjs rendering on desktop screens
hence I had a CSS style that resets my height and width to auto on screens greater than 767px.
Also, I set option maintainAspectRatio : false
as per the chartJS docs.
#canvas-container {
height: 60vh;
width: 60vw;
position: relative;
}
@media (min-width: 768px) {
#canvas-container {
height: auto;
width: auto;
}
}
<div id="canvas-container">
<Bar options={options} data={data}/>
</div>
Do not forget to set option maintainAspectRatio : false
You can check out the main example from ChartJS Docs here. Hope this helps :)
Upvotes: 1
Reputation: 130660
I've made you a demo page of how I've made my charjs responsive.
Basically you need to give the <canvas>
element height:100%
and pass these options:
options: {
maintainAspectRatio : false
}
Do not use responsive: true
at all, it doesn't seem to do anything.
If you'r <canvas>
is inside some container, I would suggest making that container responsive (with flexbox for example).
Upvotes: 19