react-apexcharts icon indicating copy to clipboard operation
react-apexcharts copied to clipboard

Charts is not fit to parent until screen is resized

Open HyunnoH opened this issue 5 years ago • 44 comments

Hi, I am using react-apexcharts and set height as fixed 300px. I thought the chart's width should be set typed or fit to parent tag. But when I using react-apexcharts, it overs parent div.

Here is my chart code:

export default function ProjectStatusGraph() {
  const options = {
    chart: {
      toolbar: {
        show: false,
      },
      id: 'project-status-graph',
    },
    dataLabels: {
      enabled: false,
    },
    stroke: {
      curve: 'smooth',
    },
    xaxis: {
      type: 'datetime',
      labels: {
        show: true,
        showDuplicates: true,
        datetimeUTC: true,
      },
    },
  };

  const activatedProjectMock = projectUsageMock
    .map(r => [Number(r.date), r.projects.filter(p => p.activated).length])
    .sort((a, b) => a[0] - b[0]);
  const workingProjectMock = projectUsageMock
    .map(r => [Number(r.date), r.projects.filter(p => p.activated && p.usage > 10).length])
    .sort((a, b) => a[0] - b[0]);

  return (
    <Card title="Project Activated / Working" size="small">
      <ReactApexChart
        options={options}
        series={[
          {
            name: 'activated',
            data: activatedProjectMock,
          },
          {
            name: 'working',
            data: workingProjectMock,
          },
        ]}
        height={300}
        type="area"
      />
    </Card>
  );
}

And here is behavior: ezgif com-video-to-gif

The chart is overflowed until I adjust screen width or some re-rendering. Is it a bug or correct behavior of apexcharts which can be handled by developer?

HyunnoH avatar Jun 15 '20 08:06 HyunnoH

I have a similar problem. I have two charts on one page and if the page gets resized, the charts get bigger, but not small again.

This is my implementation: https://gist.github.com/ckienast/261b919257dd598afc1aa27b5f41277b

ckienast avatar Jun 16 '20 10:06 ckienast

I fixed this by redeclaring apex object. I seems apexcharts needs re-rendering to find and get parent tag's size.

here is my gist about how I avoided this issues.

+++ I'm sorry that I let you know wrong information. useEffect() function did make a change, not re-declaring object.

HyunnoH avatar Jun 17 '20 07:06 HyunnoH

I'm also experiencing this when a sidebar is triggered in and out. The flow, via images, is:

Sidebar starts off opened: Screen Shot 2020-06-19 at 05 58 27

Sidebar is closed: (note the shift) Screen Shot 2020-06-19 at 05 58 34

Sidebar is re-opened: Screen Shot 2020-06-19 at 05 58 40

Implementation: https://gist.github.com/kkirsche/3aa5d3a790fbee627d3cca1f5454b3f8

Any tips on how to fix this would be greatly appreciated

kkirsche avatar Jun 19 '20 10:06 kkirsche

Please specify the version of apexcharts as well as react-apexcharts as this was an old issue already fixed.

junedchhipa avatar Jun 26 '20 10:06 junedchhipa

"apexcharts": "^3.19.2" "react-apexcharts": "^1.3.7"

ckienast avatar Jun 26 '20 10:06 ckienast

same versions on my side as @ckienast

kkirsche avatar Jun 26 '20 10:06 kkirsche

I also have a similar issue with the last version when I set the height as props. It is described in the issue #180

francoiscabrol avatar Jul 15 '20 12:07 francoiscabrol

Hi, I have the same problem. Any solution? The issue #180 that @francoiscabrol comments blocks the animations.

oscarcornejo avatar Aug 15 '20 02:08 oscarcornejo

I have the same problem when using angular material and sidenav. Latest Apexcharts from npm.

JalmariO avatar Nov 03 '20 04:11 JalmariO

Same behavior here. Charts will not fit into parent container until the first update of their data. Any ideas? I tried loading the data "delayed" by loading them inside useEffect(), but it did not help. I also tried to invoke window.dispatchEvent(new Event('resize')); but that did not chance anything either.

philipp-schmidt avatar Nov 09 '20 00:11 philipp-schmidt

Hi, I have the same problem but it seems random, here I have 2 charts, one can be resized the other, doesn't resize at all.

https://codesandbox.io/s/grid-layout-react-apexcharts-2jdo2?file=/src/App.js

In the side window it does work but if you click on (Open in new window) and resize, it won't work on the 2nd chart.

If I open the dev tools and resize the whole window, then both charts work.

I am using latest version of both Apexcharts and react-apexcharts.

Is there a fix for this?

Update: Ok so after a few tests, a way to fix the resizing issue was to access the chart ref and call the following method on the mounted event:

setTimeout(() => {
  let chartInstance = ApexCharts.getChartByID(id);
  
  if (chartInstance) chartInstance.windowResizeHandler();
},800);

When mounting and unmounting the chart too quick an error occurs,

Unhandled rejection TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

I am unable to figure out how to fix it.

simplecommerce avatar Jan 06 '21 13:01 simplecommerce

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

Pavinati avatar Aug 19 '21 14:08 Pavinati

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

This entry solved the issue for me.

darkcurrent avatar Sep 03 '21 14:09 darkcurrent

I see this issue when I have multiple charts and the parent div has the following css properties: display: grid; grid-template-columns: 1fr 1fr;

Currently using versions: "apexcharts": "^3.33.0", "react-apexcharts": "^1.3.9",

It works if I instead use grid-template-columns: 50% 50%;

charliearaya avatar Jan 18 '22 08:01 charliearaya

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

This entry solved the issue for me.

thanksss!

AntonyOnScript avatar Mar 13 '22 23:03 AntonyOnScript

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

This is a nice solution but really messes up the animation when loading in. Is there another fix found?

mennovanhout avatar May 09 '22 07:05 mennovanhout

I'm also currently facing this issue.

georgesunnyt avatar May 17 '22 10:05 georgesunnyt

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

This is a nice solution but really messes up the animation when loading in. Is there another fix found?

I used "animationEnd" event instead of "mounted". Seems to work fine. Edit: This one resizes after animation is done, so it might not be the best solution.

enesbasar avatar Aug 12 '22 11:08 enesbasar

I had the same problem when my sidebar has been expanded, chart was hidden outside window. That's weird but I've added min-width: 0 to parent div and chart resizes right now.

<div style="min-width:0">
      <apexchart />
</div>

AniaKru95 avatar Aug 19 '22 15:08 AniaKru95

Hi, I have the same problem and I used the mounted event but its working only in chrome browser not in mozilla firefox.

var options = {
        colors: [function ({ value, seriesIndex, w }) {
            if (value >= 0) {
                return '#feb600'
            } else {
                return '#c1c3c1'
            }
        }, function ({ value, seriesIndex, w }) {
            if (value >= 0) {
                return '#3ca2db'
            } else {
                return '#415364'
            }
        }],
        series: [{
            name: 'Previous Period',
            data: previousYearDataByTargetLang
        }, {
            name: 'Current Period',
            data: currentYearDataByTargetLang
            }],
        chart: {
            type: 'bar',
            height: xAxisTargetLang.length <= 8 ? 430 : xAxisTargetLang.length * 60
            , toolbar: {
                show: false
            }, events: {
                mounted: (chart) => {
                    chart.windowResizeHandler();
                }
            },
            fontFamily: 'Noto Sans, sans- serif'
        },
        plotOptions: {
            bar: {
                horizontal: true,
                dataLabels: {
                    position: 'top',
                },
            }
        },
        dataLabels: {
            enabled: false
        },
        stroke: {
            show: true,
            width: 1,
            colors: ['#fff']
        },
        tooltip: {
            shared: true,
            intersect: false,
            y: {
                formatter: function (value, { series, seriesIndex, dataPointIndex, w }) {
                    return "$" + addThousandSeperator(Math.round(value))
                }
            }
        },
        xaxis: {
            labels: {
                formatter: function (val, index) {
                    return addThousandSeperator(val.toFixed(0));
                }
            },
            categories: xAxisTargetLang,
        }

    };   
    var chart = new ApexCharts(document.querySelector("#TargetLanguageChart"), options);
    chart.render();

https://user-images.githubusercontent.com/117825585/200823025-8c766617-f6b7-4b7d-8f79-51bf13cdd18a.mp4

shazyQ avatar Nov 09 '22 12:11 shazyQ

I am having the same issue with version V3.31.0. A quick workaround that has been working for me so far is to use jQuery's document ready function and resizing the window with the event dispatcher. It's not the most ideal, but it works for me.

$( document ).ready(function() {
    window.dispatchEvent(new Event("resize"));
});

AmarokStudios avatar Feb 23 '23 22:02 AmarokStudios

Here is the solution for react.js I faced the same issue: when I close sidebar the chart not changing its width and when sidebar is open chart width overflows to parent. On resizing window it works fine, but if we don't resize window it only changes its width according to parent when reRender. I am using react and I fixed this issue by reRender chart component when sidebar is open or close.

useEffect(() => { const timeOut = setTimeout(() => { setRender(isOpen); }, 500); return () => clearTimeout(timeOut); }, [isOpen]);

In this updated code, the useEffect hook now depends on the isOpen state variable. Whenever the value of isOpen changes, the hook sets the render state variable to the value of isOpen. This causes the chart component to rerender whenever the sidebar is opened or closed.

By doing this, the chart component's width is now correctly updated whenever the sidebar is opened or closed.

Haseeb-Ahmed-HA avatar Mar 01 '23 07:03 Haseeb-Ahmed-HA

"apexcharts": "^3.37.0"

Still in issue in this latest version. Sidebar will randomly cause resizing issues with my "line" chart. current resolution seems to be utilizing the useEffect hook to force rerender.

  useEffect(() => {
    const timeOut = setTimeout(() => {
      const chartInstance = ApexCharts.getChartByID("visits-chart")
      if (chartInstance) chartInstance.updateSeries(series, true)
    }, 500)
    return () => clearTimeout(timeOut)
  }, [sidebarIsOpen])

chartInstance.updateSeries() takes two parameters, the chart data, and a boolean value forcing a new animation. Hope this helps. By the way this issue only seems to occur with the line chart. Let me know if anyone else is still experiencing this issue.

Zoot01 avatar Mar 14 '23 14:03 Zoot01

I have the same problem. In the meantime I used the mounted event as a work-around the issue.

  const chartOptions = {
    chart: {
      events: {
        mounted: (chart) => {
          chart.windowResizeHandler();
        }
      }
    }
  };

This is a nice solution but really messes up the animation when loading in. Is there another fix found?

I used "animationEnd" event instead of "mounted". Seems to work fine. Edit: This one resizes after animation is done, so it might not be the best solution.

yeah, it add this weird effect after the animation. need the the animation and width work together.

Coderamrin avatar Aug 06 '23 04:08 Coderamrin

Is there any solution for this?

Coderamrin avatar Aug 06 '23 06:08 Coderamrin

Is there any solution for this?

don't know if it helps but try adding a setTimeout when calling the chart.windowResizeHandler(); of say 800 after the mounted is called.

simplecommerce avatar Aug 07 '23 13:08 simplecommerce

Is there any solution for this?

don't know if it helps but try adding a setTimeout when calling the chart.windowResizeHandler(); of say 800 after the mounted is called.

Will try it out.

A quick note here: I just discovered the horizon UI dashboard template uses apexchart in next js and it seems to work smoothly. currently inspecting their code. Will let you guys know if i find any fix.

here's the template if anyone intersted: https://github.com/horizon-ui/horizon-ui-chakra-nextjs

Coderamrin avatar Aug 07 '23 14:08 Coderamrin

i have the same problem, for some reason some of the charts resize some dont, for now what i am doing is that:

useEffect(() => {
    const timeout = setTimeout(() => {
      window.dispatchEvent(new Event('resize'));
    }, 500)    
    return () => {
      clearTimeout(timeout)      
    }
  }, [open])

it works, but is there a better solution?

kaio-eduardo avatar Aug 08 '23 00:08 kaio-eduardo

can you please share the context where you added this code snippet?

Coderamrin avatar Aug 08 '23 07:08 Coderamrin

Please find the snippets below, hope that will help.

chart: { type: 'bar', height: 430, events: { mounted: (chart) => { chart.windowResizeHandler(); } }, },

shazyQ avatar Aug 08 '23 07:08 shazyQ