Search code examples
reactjschart.jsreact-chartjs-2

Why are some react-chartjs-2 options being ignored?


I have this simple line chart that I am trying to change the gridlines from their default gray, however the options object appears to be selectively working. Maybe I am missing something basic but I have been fiddling with it for hours and cannot get it to work, any help is appreciated! I am using "react-chartjs-2".

Below is my render() method where I pass the data and options.

render() {
        const data = {
            labels: this.state.realTimes,
            datasets: [
                {
                    label: "Price",
                    data: this.state.Prices,
                    fill: false,
                    backgroundColor: "rgb(255, 255, 255)",
                    borderColor: "rgba(255, 255, 255)"
                }
            ]
        };

        const options = {
            scales: {
                yAxis: {
                    beginAtZero: true, //this works

                    gridLines: {
                        color: "rgba(171,171,171,1)", //this doesn't
                        lineWidth: 0.5
                      }
                }
            }
        };
        return (
            <div>
                {this.state.loading ? (
                    this.loading()
                ) : (
                    <Line  data={data} options={options} width={600} height={160}  />
                )}
            </div>
        );
    }

Solution

  • Change scales.yAxis.gridLines to scales.yAxis.grid and it will work.

    see Grid Line Configuration from Chart.js documentation or the Grid Configuration samples page.

    Please take a look at below runnable JavaScript code and see how it works.

    Please take a look at

    new Chart('line-chart', {
      type: 'line',
      data: {
        labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        datasets: [{
          label: 'My Dataset',
          data: [65, 59, 80, 81, 56, 55, 40],
          fill: false,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.2
        }]
      },
      options: {
        scales: {
          yAxis: {
            beginAtZero: true,
            grid: {
              color: 'rgb(0 ,0 ,255)',
              lineWidth: 0.5
            }
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/chart.min.js"></script>
    <canvas id="line-chart" height="100"></canvas>