[Chartjs]-How to generate colors for unknown number of datasets in Chartjs

1👍

You can use d3 scale library to achieve that:

import * as scale from "d3-scale";


// Set amount of categories
const length = 20;

// Generate color scale
const colors = scale
  .scaleLinear()
  .domain([0, length])
  .range(["#fff", "#3B73B4"]);

// define some inline styles for illustration
const getBoxStyle = color => ({
  margin: "20px",
  backgroundColor: `${color}`
});

And then we simply use the generated scale:

function App() {
  const squares = [];

  for (let i = 0; i < length; i++) {
    squares.push(
      <div style={getBoxStyle(colors(i))} key={i}>
        {colors(i)} {i}
      </div>
    );
  }

  return <div className="App">{squares}</div>;
}

Please see the working example here: https://codesandbox.io/s/p96vz6r5m0

Leave a comment