Change background color to gradient in react-chartjs-2

krlik 12516 picture krlik 12516 · Jun 17, 2018 · Viewed 11.5k times · Source

I have the following options and dataset:

const chartData = {
      labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      datasets: [{
        label: 'Chart',
        data: this.transformIntoArray(data),
        backgroundColor: 'linear-gradient(to right, #20f08b, #07dfb1)',
        borderColor: '#05deb3'
      }]
    }

But it does nothing. Im using it as react component and don't know how can I reach the context of the canvas in this case. And also I render many of these charts.

        <Line
          data={chartData}
          options={options}
          height={50}
          width={300}
        />

This how I added the gradient to my chart when I was uisng chart.js in not-react app:

var gradient = this.ctx.createLinearGradient(0, 0, document.getElementById(this.id).width, document.getElementById(this.id).height);
    gradient.addColorStop(0, '#20f08b');
    gradient.addColorStop(0.5, '#20f08b');
    gradient.addColorStop(1, '#07dfb1');
    document.getElementById(this.id).style.backgroundColor = 'transparent';

    this.updatedData = {
      labels: labels,
      datasets: [{
        label: 'gradient chart',
        data: this.data,
        backgroundColor: gradient,
        borderColor: gradient
      }]
    };

How knows how to add the gradient to the Line in the react-chartjs-2 ?

@Boy With Silver Wings,

I dont quite understand how can I use this.

This what I've done for now using this method:

render() {

const getData = (canvas) => {
      const ctx = canvas.getContext("2d");
      const gradient = this.ctx.createLinearGradient(0, 0, 300, 0);
      gradient.addColorStop(0, '#20f08b');
      gradient.addColorStop(0.5, '#20f08b');
      gradient.addColorStop(1, '#07dfb1');

      return {
        labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
        datasets: [{
          label: 'Chart',
          data: this.transformIntoArray(data),
          backgroundColor: gradient,
          borderColor: '#05deb3'
        }]
      }
    }

    const canvas = document.createElement('canvas');
    const chartData = getData(canvas);

    return (
     <Line
      data={chartData}
      options={options}
      height={50}
      width={300}
    />
   )

But it says me TypeError: Cannot read property 'createLinearGradient' of undefined at getData

Answer

Agney picture Agney · Jun 17, 2018

You can add the gradients to react-chartjs in the same way.

render() {
  const data = (canvas) => {
  const ctx = canvas.getContext("2d")
  const gradient = ctx.createLinearGradient(0,0,100,0);
  ...
    return {
        ...
        backgroundColor: gradient
        ...
    }
  }

  return (
    <Line data={data} />
  )
}

Find the documentation here

See a live version here