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)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay