Home > front end >  How to return JSX from a callback in ChartJS?
How to return JSX from a callback in ChartJS?

Time:01-19

I'm using react-chartjs-2 in a React app and I would like to put JSX code into the Y axis. When I try this it only displays [Object object].

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            y: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, ticks) {
                        return <p>This is JSX</p>;
                    }
                }
            }
        }
    }
});

How can I create a Chart with JSX elements?

CodePudding user response:

Short answer: You can't

Explanation:
Since chart.js is a canvas based library it does not use dom elements to display things on the chart. For this you will need to use a svg library like recharts.

So by default you are bound to what the callback enables you to do. If you want more customization you will need to write a custom plugin that uses the canvas API to draw the things you want on the canvas itself.

https://www.w3schools.com/html/html5_canvas.asp https://www.chartjs.org/docs/4.2.0/developers/plugins.html

  • Related