Search code examples
javascriptreactjsapexcharts

React ApexCharts Donut Disappears


I am new to React apexcharts and please forgive me if I am asking a silly question. I am making a Age group chart with type of 'Donut'.

My code is like below. My issue is: The donut chart does not stay on the screen. When I first come to the page, it displays but if I refresh the page or resize the browser (Safari/chrome..), it disappears.

I appreciate it any advice or help.

import React, { useState, useEffect } from 'react'
import { Col } from 'antd'
import Chart from 'react-apexcharts'
import { endpoints, useApi } from 'src/api.context'

export const AgeDonut = () => {
  const ageGroups = ['<18', '18-25', '26-49', '50-69', '70+']
  const [ageGroupCounts, setAgeGroupCounts] = useState(ageGroups)

  const api = useApi()

  useEffect(() => {
    fetchAgeGenderData()
  }, [])

  const fetchAgeGenderData = () => {
    const params = {
      age_groups: ageGroups,
    }

    api.get(endpoints.PATIENT_STATS, params).then(
      (response) => {
        const data = response.data
        setAgeGroupCounts(data.age_stats[1])
      },
      (error) => {}
    )
  }

  const options = {
        title: {
          text: 'Age',
            align: 'left',
        },
        labels: [...ageGroups],
        responsive: [
          {
            breakpoint: 480,
            options: {
              chart: {
                width: 300,
              },
              legend: {
                position: 'bottom',
              },
            },
          },
        ],
    }

  return (
    <Col>
      <Chart
        options={options}
        series={ageGroupCounts}
        type='donut'
        width='400'
      />
    </Col>
  )
}


Solution

  • Can you create a minimal working codesandbox? Maybe you are missing the height in the options?

    const options = {
      // Other options here...
      height: 400, // Set the height of the chart
    };
    
    return (
      <Col>
        <Chart
          options={options}
          series={ageGroupCounts}
          type="donut"
          width="400"
        />
      </Col>
    );
    

    Alternatively, you can also use the responsive property to set the height of the chart based on the width of the container element. Here is an example:

    const options = {
      // Other options here...
      responsive: [
        {
          breakpoint: 480,
          options: {
            chart: {
              width: 300,
              height: 200, // Set the height of the chart
            },
            legend: {
              position: 'bottom',
            },
          },
        },
      ],
    };
    
    return (
      <Col>
        <Chart
          options={options}
          series={ageGroupCounts}
          type="donut"
          width="400"
        />
      </Col>
    );