'How to add gradient to a line chart in reactjs
So I want to add gradient to my line chart in reactjs.Problem i am facing that I am importing this chart as a component in a different component.So when I apply the createLinearGradient method I need to get the id or class of the element.
const ctx = document.getElementById('linechart').getContext("2d");
var gradient = ctx.createLinearGradient(0, 0, 0,300);
gradient.addColorStop(0, 'rgba(242, 153, 74, 0.5)');
gradient.addColorStop(1, 'rgba(242, 153, 74, 0)');
Problem I am facing is where should I add this piece of code.If I add this inside the function where I am making the chart,its of no use since it gives error because that component has not been rendered yet.This is my chart component code:
import React from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
const chart = () => {
const data = {
labels:['Sun','Mon','Tue,','Wed','Thu','Fri','Sat'],
datasets: [
{
label: 'Sales'
data: [1,2,3,4,5,6,7],
borderColor:['#F2994A'],
backgroundColor: gradient
tension: 0.3,
fill: true
}
]
}
const options = {
responsive: true,
elements: {
point:{
radius: 0
}
},
maintainAspectRatio: false,
plugins: {
legend: false,
},
scales: {
y: {
grid: {
display: false
},
}
}
}
return (
<Line id='linechart' data={data} options={options} />
)
};
How to set the gradient of background of my line chart after it has been rendered?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
