I'm working on a React project where I need to display a Chart.js chart inside a parent component which is in grid layout. The chart should resize according to its parent container while maintaining a fixed aspect ratio of 3.5:1 (width: height). However, I'm struggling to make the chart responsive without hardcoding its dimensions.
Here's my current setup:
Parent Component
<div className="graph_container">
<h4>{title}</h4>
<div className="graph_container_graph">
<DynamicLineChart data={data} key={JSON.stringify(data)} />
</div>
</div>
Parent Component's Styles
.graph_container {
width: 100%;
max-width: fit-content;
border-radius: 1.27rem;
background-color: #fff;
padding: 0.95rem;
display: flex;
flex-direction: column;
gap: 0.63rem;
font-size: 1.4rem;
}
.graph_container_graph {
padding: 0 0.95rem;
}
DynamicLineChart Component
import React, { useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);
const DynamicLineChart = ({ data }) => {
const chartData = {
labels: Object.keys(data),
datasets: [
{
data: Object.values(data),
fill: false,
backgroundColor: '#FFF',
borderColor: '#6497FC',
borderWidth: 3,
pointBackgroundColor: '#4D5C92',
pointBorderColor: '#4D5C92',
pointRadius: 5,
pointHoverRadius: 5,
},
],
};
const options = {
aspectRatio: 3.5,
maintainAspectRatio: true,
layout: {
padding: {},
},
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: true,
},
},
scales: {
x: {
grid: {
borderDash: [15, 5],
color: '#CDD1DB',
borderColor: '#CDD1DB',
},
ticks: {
color: '#6B7280',
font: {
size: 10,
},
},
},
y: {
min: 0,
max: 100,
ticks: {
font: {
size: 10,
},
stepSize: 25,
color: '#6B7280',
},
grid: {
display: false,
},
},
},
};
return (
<div style={{ width: '100%', height: 'auto' }}>
<Line data={chartData} options={options} />
</div>
);
};
export default DynamicLineChart;
The **Problem **is that Currently, the chart is not responsive unless I hardcode its width and height. I want the chart to resize based on its parent container's width, maintaining the aspect ratio of 3.5:1. How can I achieve this?
What I've Tried
- Setting
maintainAspectRatio
to true in the chart options. - Wrapping the
Line
component in a div with a percentage-based width. - Using CSS to control the parent container's size. None of these solutions have worked as expected. The chart does not resize properly and often breaks the layout.
I need the chart to adjust its width dynamically based on the parent container while keeping the height proportional to the width with an aspect ratio of 3.5:1.
Any help or suggestions would be greatly appreciated!