You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Check this if you would like to implement a PR, we are more than happy to help you go through the process.
Current and expected behavior
I was checking the docs for the Line component and I noticed that if I resize the preview and make it smaller the chart shrinks (that is correct), but when I give it more space it doesn't grow, try it here https://react-chartjs-2.js.org/examples/line-chart/
Hey, @vrde and @diegotraid, I found that adding an explicit resize() fixed the problem. Here's my function, bwChart being the name of my chart instance:
function chartWide() {
bwChart.options.plugins.title.display = false;
bwChart.options.plugins.legend.position = 'right';
bwChart.options.plugins.legend.title.display = true;
bwChart.options.plugins.legend.title.position = 'start';
bwChart.update();
bwChart.resize(); // without this, it'll only shrink, not grow
}
@imbwaldo
Unfortunately it does not, or at least, it does not in an acceptable and stable way. For me, during resizing to grow, it flickers in size all the time, and what size it ends up with depends on the current moon-phase.
The only way to fix it reliably that I found, is to set maintainAspectRatio: false in options, and implement my own resize-observer logic, and enforce the width and height values via the ref.current?.resize(w, h) call. The downside is that this requires me to look after the aspect ratio on my own (if I need it maintained).
I don't know if this is relevant, but I had the same issue while working in an Electron-React project: and It was caused by updating the chart's width with className dynamically rather than with style. Rookie mistake, but I hope someone finds this useful.
I am attempting to make the switch from chartjs to react-chartjs-2 and ran into this exact issue.
My chartjs config works as intended when using the library only, however when using this one it does not.
I've tried making a plugin to strip the size information from the canvas and styling which didn't work.
Also I see here:
And just to be abundantly clear, this works perfectly, it's responsive and grows to it's parent:
import{Chart}from"chart.js";import{BasePriceChartConfig,PriceChartOptions}from"./chart";exportclassBrowserPriceChartConfigextendsBasePriceChartConfig{constructor(options: PriceChartOptions){super(options);}publiccreateChartElement(){constelement=document.createElement("canvas");constchart=newChart(element,this.chartConfig);return{ chart, element };}}
Which leads me to believe the problem is on this side and not chartjs.
Okay this is a follow up to my previous comment, the solution for me was to re-implement the whole thing, important note is that the chart is redrawn entirely every time the screen size changes.
If it helps anyone here is the code:
importtype{ChartType,DefaultDataPoint}from"chart.js";import{ChartasChartJS}from"chart.js";importReact,{forwardRef,useEffect,useRef}from"react";importtype{BaseChartComponent,ChartProps,ForwardedRef}from"./types";import{cloneData,reforwardRef,setDatasets,setLabels,setOptions,}from"./utils";functionChartComponent<TTypeextendsChartType=ChartType,TData=DefaultDataPoint<TType>,TLabel=unknown,>(props: ChartProps<TType,TData,TLabel>,ref: ForwardedRef<ChartJS<TType,TData,TLabel>>,){const{
datasetIdKey,
type,
data,
options,
plugins =[],
fallbackContent,
updateMode,
...canvasProps}=props;constcanvasRef=useRef<HTMLCanvasElement>(null);constcontainerRef=useRef<HTMLDivElement>(null);constchartRef=useRef<ChartJS<TType,TData,TLabel>|null>(null);constdestroyChart=()=>{if(chartRef.current){chartRef.current.destroy();chartRef.current=null;}if(canvasRef.current){constctx=canvasRef.current.getContext("2d");if(ctx)ctx.clearRect(0,0,canvasRef.current.width,canvasRef.current.height);// Reset width and height to avoid forced valuescanvasRef.current.removeAttribute("width");canvasRef.current.removeAttribute("height");}reforwardRef(ref,null);};constrenderChart=()=>{if(!canvasRef.current||!containerRef.current)return;destroyChart();// Ensure previous instance is removed// Set explicit width and height from container before renderingcanvasRef.current.style.width="100%";canvasRef.current.style.height="100%";canvasRef.current.removeAttribute("width");canvasRef.current.removeAttribute("height");chartRef.current=newChartJS<TType,TData,TLabel>(canvasRef.current,{
type,data: cloneData(data,datasetIdKey),options: {
...options,responsive: true,maintainAspectRatio: false,}asChartJS<TType,TData,TLabel>["options"],
plugins,});reforwardRef(ref,chartRef.current);};useEffect(()=>{renderChart();return()=>destroyChart();},[]);useEffect(()=>{if(chartRef.current&&options){setOptions(chartRef.current,options);chartRef.current.update(updateMode);}},[options,updateMode]);useEffect(()=>{if(chartRef.current){setLabels(chartRef.current.config.data,data.labels);setDatasets(chartRef.current.config.data,data.datasets,datasetIdKey);chartRef.current.update(updateMode);}},[data.labels,data.datasets,datasetIdKey,updateMode]);useEffect(()=>{if(!chartRef.current)return;destroyChart();setTimeout(renderChart,100);},[type]);useEffect(()=>{consthandleResize=()=>{destroyChart();setTimeout(renderChart,100);// Wait briefly before re-rendering};window.addEventListener("resize",handleResize);return()=>window.removeEventListener("resize",handleResize);},[]);returnReact.createElement("div",{ref: containerRef,style: {width: "100%",height: "400px",minWidth: "300px",// Prevents shrink-to-zero issuesminHeight: "300px",// Ensures a visible areadisplay: "flex",justifyContent: "center",alignItems: "center",},},React.createElement("canvas",{ref: canvasRef,role: "img",style: {width: "100%",height: "100%",},
...canvasProps,},fallbackContent,),);}exportconstChart=forwardRef(ChartComponent)asBaseChartComponent;
Closing: this is about how Chart.js itself behaves or is configured, while react-chartjs-2 passes data, options and plugins to Chart.js as they are. The Chart.js docs cover it: https://www.chartjs.org/docs/latest/ If it turns out to be a bug, please report it to Chart.js: https://github.com/chartjs/Chart.js/issues
It is fixed in Chart.js 4.6.2 (chartjs/Chart.js#12421): responsive charts grow back in containers sized by their content.
Activity
vrde commentedon Jun 13, 2023
👋 any update on this?
diegotraid commentedon Jun 30, 2023
Hi! You should wrap the chart component within a
<div>with position relative and width and height values set.More on this: https://www.chartjs.org/docs/latest/configuration/responsive.html
Working example (based on the one you are referring to): here
Note that the
maintainAspectRatiooption is set tofalse.vrde commentedon Jul 10, 2023
@diegotraid thanks for your answer! I'm a bit surprised this configuration isn't the default one as responsive widgets are more or less the default 😄
I'll implement your suggestions.
GeorgeFlorian commentedon Aug 11, 2023
Every example from your websites: https://react-chartjs-2.js.org/examples and https://www.chartjs.org/docs/latest/samples/information.html suffers from this bug: the charts only shrink.
@diegotraid
Also, your working example is not a valid link: https://46yzc4-5173.csb.app/
diegotraid commentedon Aug 11, 2023
Sorry about the wrong link, check again.
imbwaldo commentedon May 10, 2024
Hey, @vrde and @diegotraid, I found that adding an explicit
resize()fixed the problem. Here's my function,bwChartbeing the name of my chart instance:Hope that works for you, too.
kostia1st commentedon Jul 1, 2024
@imbwaldo
Unfortunately it does not, or at least, it does not in an acceptable and stable way. For me, during resizing to grow, it flickers in size all the time, and what size it ends up with depends on the current moon-phase.
The only way to fix it reliably that I found, is to set
maintainAspectRatio: falsein options, and implement my own resize-observer logic, and enforce the width and height values via theref.current?.resize(w, h)call. The downside is that this requires me to look after the aspect ratio on my own (if I need it maintained).imbwaldo commentedon Jul 15, 2024
Thanks, @kostia1st. I eventually found this worked for me (see last two lines):
Don't know if that'll work for you, too. Hope so. Thanks again for your reply!
fellipeParreiras commentedon Oct 11, 2024
I don't know if this is relevant, but I had the same issue while working in an Electron-React project: and It was caused by updating the chart's width with
classNamedynamically rather than withstyle. Rookie mistake, but I hope someone finds this useful.RampantDespair commentedon Feb 18, 2025
I am attempting to make the switch from
chartjstoreact-chartjs-2and ran into this exact issue.My chartjs config works as intended when using the library only, however when using this one it does not.
I've tried making a plugin to strip the size information from the canvas and styling which didn't work.
Also I see here:
react-chartjs-2/src/chart.tsx
Line 23 in d95f040
react-chartjs-2/src/chart.tsx
Line 24 in d95f040
that the default values are 300x150 which is exactly what I see on my HTML element in browser.
Is it possible to get rid of the sizing completely? Passing undefined doesn't work either.
And just to be abundantly clear, this works perfectly, it's responsive and grows to it's parent:
Which leads me to believe the problem is on this side and not
chartjs.Any help or idea is appreciated
RampantDespair commentedon Feb 20, 2025
Okay this is a follow up to my previous comment, the solution for me was to re-implement the whole thing, important note is that the chart is redrawn entirely every time the screen size changes.
If it helps anyone here is the code:
bhaktijkoli commentedon Aug 21, 2025
I solved by adding a span below the chart.
Cyberfly100 commentedon Oct 21, 2025
Nice, this worked for me with slight modification:
dangreen commentedon Nov 30, 2026
Closing: this is about how Chart.js itself behaves or is configured, while react-chartjs-2 passes
data,optionsandpluginsto Chart.js as they are. The Chart.js docs cover it: https://www.chartjs.org/docs/latest/ If it turns out to be a bug, please report it to Chart.js: https://github.com/chartjs/Chart.js/issuesIt is fixed in Chart.js 4.6.2 (chartjs/Chart.js#12421): responsive charts grow back in containers sized by their content.