How to update tootltip title text of c3.js dynamically in React?

16 views Asked by At

I want to update the title text of my c3.js chart tooltip whenever a prop in my React component updates. How do I go about doing this.

The naive approach is to set it during the creation of the chart:

const Chart = ({ titleText }) => {
  const [chart, setChart] = useState(null);

  useEffect(() => {
      const plots = createSomeDataSeries();
      setChart(
        c3.generate({
          bindto: '#chart',
          unload: true,
          data: {
            type: 'line',
            columns: plots,
          },
          tooltip: {
            format: {
              title: (_, __) => selection, // <-- Value is constant from when chart is drawn
              name: (_, __, id, index) => {
                const episode = data[id.split(' ').slice(-1) - 1][index];
                return "some text";
              },
            },
          },
          // More config...
        })
      );
    }
  }, []);

  return <div id="chart" />
};

This obviously won't work since it is only set during the initial draw of the chart. However, I tried something like this, but it didn't work:

const Chart = ({ titleText }) => {
  const [chart, setChart] = useState(null);

  useEffect(() => {
    chart?.tooltip({
      format: {
        title: () => selection,
      },
    });
  }, [selection]);

  useEffect(() => {
    const plots = createSomeDataSeries();
    setChart(
      c3.generate({
        bindto: '#chart',
        unload: true,
        data: {
          type: 'line',
          columns: plots,
        },
        tooltip: {
          format: {
            title: (_, __) => selection,
            name: (_, __, id, index) => {
              const episode = data[id.split(' ').slice(-1) - 1][index];
              return "some text";
            },
          },
        },
        // More config...
      })
    );
  }, []);

  return <div id="chart" />
};

Any ideas on how to get it working?

0

There are 0 answers