简体   繁体   中英

How to make react-chartjs-2 responsive on mobile?

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

这是它在小型设备上的显示方式

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).

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM