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

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay