Search code examples
javascriptreactjschartscarbon-design-system

How to set colors in react carbon design chart


I'm using the react library of carbon design charts and I'm having difficulties setting custom colors using getFillColor function in the chart options properties :

import React from "react";
import ReactDOM from "react-dom";
import { DonutChart } from "@carbon/charts-react";
import "@carbon/charts/styles.css";

const colors = {
  java: "#FF0000",
  javascript: "#00FF00",
  "c++": "#0000FF"
};

const chartData = [
  {
    group: "java",
    value: 300
  },
  {
    group: "javascript",
    value: 600
  },
  {
    group: "c++",
    value: 200
  }
];

const demoDonutOptions = {
  getFillColor: (field) => {
    return colors[field];
  },
  height: "300px"
};

function App() {
  return (
    <div className="App">
      <h3>React Donut chart with label</h3>
      <div>
        <DonutChart data={chartData} options={demoDonutOptions} />
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The code above works in v0.40.2 and below, checkout this sandbox, it correctly set the colors :

enter image description here

but in v0.40.3 and above, it doesn't work anymore, see this sandbox, the colors remain unchanged :

enter image description here

What is the correct way of setting colors in carbon design chart framework ?


Solution

  • I've found out that from the history, there was a change that needs the color.scale property to be specified in the chart options:

    const demoDonutOptions = {
      color: {
        scale: {
          java: "#FF0000",
          javascript: "#00FF00",
          "c++": "#0000FF"
        }
      },
      height: "300px"
    };
    

    Note that all the groups need to be specified in color.scale for this example to be working :

    import React from "react";
    import ReactDOM from "react-dom";
    import { DonutChart } from "@carbon/charts-react";
    import "@carbon/charts/styles.css";
    
    const colors = {
      java: "#FF0000",
      javascript: "#00FF00",
      "c++": "#0000FF"
    };
    
    const chartData = [
      {
        group: "java",
        value: 300
      },
      {
        group: "javascript",
        value: 600
      },
      {
        group: "c++",
        value: 200
      }
    ];
    
    const demoDonutOptions = {
      color: {
        scale: colors
      },
      height: "300px"
    };
    
    function App() {
      return (
        <div className="App">
          <h3>React Donut chart with label</h3>
          <div>
            <DonutChart data={chartData} options={demoDonutOptions} />
          </div>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    Checkout this sandbox

    It's also possible to use getFillColors which overrides the color.scale but it seems the color.scale is compulsory at this time