12👍
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).
- [Chartjs]-Chart.js horizontal bar width
- [Chartjs]-How to fix chart Legends width-height with overflow scroll in ChartJS
1👍
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 🙂
0👍
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} />;
}