DEV Community

Cover image for How to map colors & labels in ApexChart
Chinthaka Bandara
Chinthaka Bandara

Posted on

How to map colors & labels in ApexChart

Problem
When using a donut/pie chart it is mapping the colors in the array to labels in the label order. If there is no value for a particular label, then the whole thing gets messed up. This is a big issue when presenting data that doesn't always come in a predefined order.

Solution
When passing data from the API, pass the colors also in the same order as labels. This way colors of missing labels won't be in the colors array. You have to send the color codes in Hex (#ffffff) format.

const chartOptions = {
    labels: chartData?.labels || [],
    colors: chartData?.colors || [],
        ...
};
Enter fullscreen mode Exit fullscreen mode
<Chart 
    options={chartOptions} 
    series={chartData?.series || []} 
    type='donut' 
    height={300} 
/>
Enter fullscreen mode Exit fullscreen mode

Happy Coding 😉

Top comments (0)