Reputation: 1
I’m working on customizing a line chart in Chart.js for the application I’m building, but I’ve been unable to apply the theme styling from my GlobalStyle setup. I’m using styled-components for my app. I also attempted to dynamically adjust the Chart.js colors, but I encountered an error (see the attached image).
Is there a way to apply my theme props here? The main reason is that my app has a dark/light mode feature, and this is the only approach I know to easily toggle the colors of my elements.
Here’s the code for my chart component:
import React, { useEffect, useState } from 'react';
import { Chart as ChartJS, LineElement, PointElement, LinearScale, Title, Tooltip, CategoryScale } from 'chart.js';
import { Line } from 'react-chartjs-2';
import styled from 'styled-components';
ChartJS.register(LineElement, PointElement, LinearScale, Title, Tooltip, CategoryScale);
const LineChart = ({ theme }) => {
// state variables
const [dataType, setDataType] = useState('Income'); // stores current data type (income, expenses, savings)
const [isDropdownOpen, setIsDropdownOpen] = useState(false); // manages dropdown state (open/close)
const [timeRange, setTimeRange] = useState('6 Months'); // stores current time range (by month)
// chart data & style
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [
{
label: dataType,
data: dataType === 'Income' ? [3000, 4000, 3200, 4500, 4800, 5300] :
dataType === 'Expenses' ? [2500, 3000, 2800, 3500, 3700, 3900] :
[500, 1000, 400, 1000, 1100, 1400],
fill: false,
backgroundColor: theme.containerBackground,
borderColor: theme.borderColor,
pointBorderColor: theme.textColor,
pointBackgroundColor: theme.textColor,
tension: 0.3,
pointRadius: 5,
pointHoverRadius: 7,
},
],
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: true,
backgroundColor: theme.textColor,
titleColor: '#fff',
borderColor: '#ccc',
borderWidth: 1,
bodyColor: "#ddd",
},
},
scales: {
x: {
grid: {
display: false,
},
// x-axis label
ticks: {
color: theme.textColor,
stepSize: 400
},
},
y : {
beginAtZero: true,
grid: {
color: theme.textColor,
},
// y-axis label
ticks: {
color: theme.textColor,
font: {
size: 14,
},
},
},
},
};
return (
<Container theme={theme}>
{/* other elements */}
<ChartContainer>
<Line data={data} options={options} />
</ChartContainer>
</Container>
);
};
export default LineChart;
I tried to customize this line chart by mapping these colors into Chart.js configuration and dynamically adjust the styling, but I encountered an error (see the attached image).
Upvotes: 0
Views: 21