1

I'm using react-apexcharts to visualize some financial data. My chart has an option to switch the Y-axis scale between percentages and dollars. Although the scale changes correctly when I click on the respective buttons, the axis labels (symbols % and $) don't update dynamically. They only change when I do a fast refresh.

This is an example: enter link description here Here is a simplified version of my code:

import React, { useState, useEffect } from 'react';
import Chart from 'react-apexcharts';

const App = () => {
  const baseChartOptions = {
    chart: {
      type: 'line',
    },
    series: [
      {
        name: 'serie1',
        data: [1, 2, 3],
      },
    ],
    xaxis: {
      categories: ['a', 'b', 'c'],
    },
  };
  const [chartOptions, setChartOptions] = useState(baseChartOptions);
  const [scale, setScale] = useState('percentage');

  useEffect(() => {
    const getYAxisFormatter = (val) => {
      return scale === 'percentage' ? `${val.toFixed(1)}%` : `$${val.toFixed(2)}`;
    };

    setChartOptions((prevOptions) => ({
      ...prevOptions,
      yaxis: { labels: { formatter: getYAxisFormatter } },
    }));
  }, [scale]);

  return (
    <>
      <h4>{scale}</h4>
      <button onClick={() => setScale('dollars')}>Dollars</button>
      <button onClick={() => setScale('percentage')}>Percentage</button>
      <Chart options={chartOptions} series={chartOptions.series} type="bar" width="500" height="320" />
    </>
  );
};

export default App;

Thank you.

Damiano Dotto
  • 105
  • 1
  • 10

0 Answers0