Repository: recharts/recharts (2025-07-06T12:27:32Z)

Issue:
ResponsiveContainer does not respond to resizing from large to small
ResponsiveContainer computes the size of the chart based on the current window size. It also seems to respond when you make the browser window larger, however if you make the browser window smaller, the chart stays large. Tested on chrome. 



Discussion:
@marchaos It works fine in [this demo](http://jsfiddle.net/znqLLdev/1/?utm_source=website&utm_medium=embed&utm_campaign=znqLLdev). Can you show your question in an online jsfiddle demo ?

hi Xile. You're correct that it does rescale. I believe the problem I'm having is that I have a chart inside a flexbox container. Since recharts is using javascript to compute the resize, I don't think that it will work with flexbox. This isn't necessarily a recharts issue (or d3.js), but I would presume that a change or config on the recharts side would be needed to achieve what I'm doing. 

@marchaos Recharts listens to the resize event of the container node. As long as you add a  `ResponsiveContainer` in to a container node,  and the container node can change size when the browser becomes larger or smaller, then the chart will change responsively. So I think it may be the bug of the layout which wrapper the ResponsiveContainer. It will be helpful to show your case in a jsfiddle demo. 

@xile611 http://jsfiddle.net/9tjsb7k2/embedded/result/. You'll see it opens to the correct size of the window, and if you resize from a small window to make it larger, it works, but not going from larger to smaller. 

@marchaos It seems to be the problem of calculation strategy for flex box. You can check this [stackoverflow question](http://stackoverflow.com/questions/7985021/css-flexbox-issue-why-is-the-width-of-my-flexchildren-affected-by-their-content) for detail.

http://jsfiddle.net/oezx3kh2/embedded/result/

Thanks, adding width: 0 to the children fixed that issue!

Does anyone know the fix for `flexDirection: 'column'?` Apparently setting `width: 0` does not fix the issue here. 
I figured it out. Kind of. If you're trying to use `flexDirection: 'column'` and run into this issue, I suggest that on your `ResponsiveContainer` that you add `width={'99%'}` along with a static height, like `height={200}`. This will make the chart resize properly. Just setting `width: 0` on the parent element will not work because for some reason `flex: 1` will not override `width: 0` on the parent element. I have no idea why. According to this blog post, [http://gedd.ski/post/the-difference-between-width-and-flex-basis/](url), it should, but it doesn't. 
This problem seems to persist.
got it working with a 99% width and a fixed height
We also got it working using 99% width. 
Working with 99% however it would be nice if this worked at 100%. I'll do some further investigating to understand how this could be resolved in a way that doesn't include hacks.
Issue is still there. 


Any suggestions? 
@domix90 I set the height/width of a parent div using percents rather than flex grow. then set the responsive grid height/width props with percents as well. Seemed to work well.

```javascript
<div style={{ height: '1000px', width: '1000px' }} >
    <div style={{ height: '100%', width: '60%' }}>
          <ResponsiveContainer height={/*some percent*/} width={/*some percent*/}>
          </ResponsiveContainer>
     </div>
</div>
```
Thanks @tmercado ! 

I decided to switch to Charts.js to avoid this issue for future projects. 
Why is this issue closed if it's still an issue and clearly a bug?

I mean, that's just pretty fucked up, should just work with 100% for width & height (and yes it only works with 99.8% for height for me, not 99.9% - or 99.99% for that matter).
![Screenshot 2019-07-12 at 13 36 58](https://user-images.githubusercontent.com/1210628/61125457-2b569180-a4aa-11e9-9815-6d1d24cd84d9.jpg)

I fixed it up using old lifehack with padding.

```
<div style={{position: 'relative', width: '100%', paddingBottom: '250px'}}>
  <div
    style={{
      position: 'absolute',
      left: 0,
      right: 0,
      bottom: 0,
      top: 0,
    }}
  >
    <ResponsiveContainer>
      <YourChartGoesHere />
    </ResponsiveContainer>
  </div>
</div>
```

paddingBottom value can be in px for fixed height, and in percents for aspect ratio.
Animations are very slow with width 99%
@olelivalife You can try to delay or debounce the resize action and only then adjust the size of the container. That means though, that you might have to set the width manually using a ref. 

http://bencentra.com/code/2015/02/27/optimizing-window-resize.html
For me, setting `overflow: hidden` in parent component solves the problem.

```jsx
<div style={{ overflow: 'hidden', 'flex-basis': "50%" }}>
  <ResponsiveContainer>
    <YourChartGoesHere />
  </ResponsiveContainer>
</div>
```
new hack for issue
set `position: relstive` for `.recharts-surface`
```
.recharts-surface {
  position: absolute !important;
  left: 0px;
  top: 0;
}
```
> .recharts-surface {
>   position: absolute !important;
>   left: 0px;
>   top: 0;
> }

@vitaliyzh 
`relative`? or `absolute`. Your snippet shows aboslute?
The issue is still there. I have a problem with the flex layout with direction "row". Screen rotation on mobile devices does not resize chart from bigger to smaller height. My solution is to use height equals 94% on ResponsiveContainer so resizing is triggered and animation is not to slow.

It will be great if any fix of this problem will come out.


UPD.

I have found a new solution on the flexbox with direction column for my case.

On a flex-container I have:
{ width: 100%; height: 100%; display: flex; flex-wrap: nowrap; }

And on the wrapper flex div over ResponsiveContainer I have:
{ flex: 1, width: '100%', overflow: 'hidden' }

UPD2: Wrapper flex must be set to { flex: 1 }. Initially, I set it to {  flex-grow: 1 }, but it does not work in the Safari.

On ResponsiveContainer height and width are set to 100%.

It seems to work properly when screen orientation on the mobile device is switched from landscape to portrait.


The jsx structure in the app is something about like this:
```jsx
<div style={{ width: '100%', height: '100%', display: 'flex', flexWrap: 'nowrap' }}>
  <div style={{ width: '100%' }}>
    Header element with some title
  </div>
  <div style={{ flex: 1, width: '100%', overflow: 'hidden' }}>
    <ResponsiveContainer
      width="100%"
      height="100%"
    >
       <YourChartComponent />
    </ResponsiveContainer>
  </div>
</div>
```

overflow is important! It must be defined on the element. Without it resize does not work properly.

And also I have a wrapper container element with a defined height upper on the component tree. This structure is injected inside this wrapper element so they together work as a widget component. The main goal is that the ResponsiveContainer is reacting to any changes of the upper wrapper component with defined height. And it does in this case.


> Animations are very slow with width 99%

Yep, I had that too. But then I tried the solution right before your comment; the [one](#issuecomment-523362671) by @mixail-novikov. It works flawlessly.
Having issues with this as well. Tried everything mentioned here, and in other issues and SO threads.  

The best I was able to do was use a width of 94% to speed up the animation, it's extremely clunky looking while resizing though.
```
    <div style={{ width: ''100%' }}>
      <ResponsiveContainer width="94%" height={450} debounce={1}>
        <BarChart
          data={chartData}
          margin={{
            top: 30,
            right: 0,
            left: 20,
            bottom: 30,
          }}
        >
...
    </div>
```

If I go any lower than 94% the bars get really out of whack in terms of being centered with the parent, using a left margin 20 and no right margin allows them to at least appear centered.

PS: Why is this issue closed? Using bs hacks like 99% and 94% with awful margins is not a solution it's a workaround for an obvious bug and/or limitation that needs to be addressed.
@reifnotreef Let us know why the [one](#issuecomment-523362671) by @mixail-novikov is not working for you. It is working for me flawlessly.
@christiaanwesterbeek it does not. I thought it might have to do with me having a div above my responsize container.
```
    <div className={classes.barGraphWrapper}>
      <div className={classes.header}>
        {title && <div className={classes.headerStyles}>{title}</div>}
        {CustomTitle && <CustomTitle />}
      </div>
      <ResponsiveContainer width="94%" height={450} debounce={1}>
        <BarChart
          data={chartData}
          margin={{
            top: 30,
            right: 0,
            left: 20,
            bottom: 30,
          }}
        >
```
I tried removing the extra header div that but it still didn't work. It causes the bar graph to be rendered at about 25% width instead of 100%.

Either way this issue should not be closed as this is not a "fix" it's a hack/workaround for an inherit problem with the ResponsiveContainer.
This should definitely not be closed. Changing the height of the container does not trigger a change in height for the chart.
> I fixed it up using old lifehack with padding.
> 
> ```
> <div style={{position: 'relative', width: '100%', paddingBottom: '250px'}}>
>   <div
>     style={{
>       position: 'absolute',
>       left: 0,
>       right: 0,
>       bottom: 0,
>       top: 0,
>     }}
>   >
>     <ResponsiveContainer>
>       <YourChartGoesHere />
>     </ResponsiveContainer>
>   </div>
> </div>
> ```
> 
> paddingBottom value can be in px for fixed height, and in percents for aspect ratio.

I can confirm this fix works.
This is a real stinker of a bug from recharts.  I was very close to ditching the library entirely
(Scroll to bottom for my super hacky custom solution that works for all use cases, it's ugly.)

Bumping this, I've been trying to fix this for 4 hours, none of the solutions works for me.

I have a complicated graph where a user can select inputs that cause the number of items in the Legend to grow over time (aka # of lines on the graph changes with user clicks).

So, some of these "fixes" (hacks around a bug) work if the graph legend is static after render.  However once lines are added over time (within the same component life cycle!) this issue comes back.

I am very very close to moving over to Charts.js since they seem to care about stuff like this?

Question to maintainers from a nice dev: Please, please, at least recognize this is a terrible bug.  This is not fixed.  I am on latest 2.0.6 and still seeing this.  It's plaguing my app and my users.  This is not acceptable.

I'd be more than happy to try to put up a PR to fix if someone can point me to the source.  I'll follow up if I find a true fix that actually works for complicated dynamic graphs for rich applications.

EDIT: This is quite literally what I had to do for my use case to work.
(The numbers in the useEffect are the lengths of user inputs that influence how many items will be rendered in the Legend, the sum of the two numbers equals the number of lines in the graph)

top of file rendering graph (both these come in as props)
```
const [hackyRechartsResizeHeight, setHackyRechartsResizeHeight] = useState('100%');

useEffect(() => {
  if (hackyRechartsResizeHeight === '100%') {
    setHackyRechartsResizeHeight('99%');
  } else {
    setHackyRechartsResizeHeight('100%');
  }
}, [numSelectedKpis, numActiveTickers]);
```
then below in the render function I have this code
```
        <div style={{height: 420, width: '100%'}}>
          <ResponsiveContainer height="100%" width={hackyRechartsResizeHeight}>
            <LineChart ...
```
fml. lol, but it works!
I pulled my hair out trying to get the `<ResponsiveContainer/>` to work with my HTML structure, but nothing from this thread or suggestions from elsewhere seemed to work. I instead ditched the responsive container completely and wrote my own hook to resize the chart based on the parent element's width. 

The hook:

```
import { useLayoutEffect, useState, RefObject } from 'react';

export const useElementSize = <T extends HTMLElement>(
  elementRef: RefObject<T>
): number[] => {
  const [size, setSize] = useState<number[]>([0, 0]);

  useLayoutEffect(() => {
    if (elementRef.current) {
      const updateSize = (): void => {
        setSize([
          elementRef?.current?.clientWidth || 0,
          elementRef?.current?.clientHeight || 0,
        ]);
      };
      window.addEventListener('resize', updateSize);
      updateSize();
      return () => window.removeEventListener('resize', updateSize);
    }
  }, [elementRef]);

  return size;
};
```

Implementation:

```
export const Chart = () => {
  const chartData = [{...}];
  const containerRef = useRef<HTMLDivElement>(null);
  const [width, height] = useElementSize(containerRef);

  return (
    <div ref={containerRef} style={{ width: "100%", overflow: "hidden" }}> // overflow: hidden is important
      <LineChart
        height={500}
        width={width} // set the chart width to the width value returned from the hook
        data={chartData}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray='3 3' />
        <XAxis dataKey='key' />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line
          type='monotone'
          dataKey='otherKey'
          stroke='#2563eb'
          activeDot={{ r: 8 }}
        />
      </LineChart>
    </div>
  );
}
```

Hope this can help others who need their chart to be responsive!
+1 Setting the width to 99% is not acceptable...
Wrapping your `useEffect` code in `setTimeout` should do the trick. But honestly, this should be fixed.

> new hack for issue
> set `position: relstive` for `.recharts-surface`
> 
> ```
> .recharts-surface {
>   position: absolute !important;
>   left: 0px;
>   top: 0;
> }
> ```

I had a similar fix, but I'm not sure why it works.

```
.recharts-wrapper {
  position: absolute !important;
}
```
> .recharts-wrapper {
>   position: absolute !important;
> }

seems to work, but this is a bit ugly, awaiting for the fix - this issue should be reopened!
> I pulled my hair out trying to get the `<ResponsiveContainer/>` to work with my HTML structure, but nothing from this thread or suggestions from elsewhere seemed to work. I instead ditched the responsive container completely and wrote my own hook to resize the chart based on the parent element's width.
> 
> The hook:
> 
> ```
> import { useLayoutEffect, useState, RefObject } from 'react';
> 
> export const useElementSize = <T extends HTMLElement>(
>   elementRef: RefObject<T>
> ): number[] => {
>   const [size, setSize] = useState<number[]>([0, 0]);
> 
>   useLayoutEffect(() => {
>     if (elementRef.current) {
>       const updateSize = (): void => {
>         setSize([
>           elementRef?.current?.clientWidth || 0,
>           elementRef?.current?.clientHeight || 0,
>         ]);
>       };
>       window.addEventListener('resize', updateSize);
>       updateSize();
>       return () => window.removeEventListener('resize', updateSize);
>     }
>   }, [elementRef]);
> 
>   return size;
> };
> ```
> 
> Implementation:
> 
> ```
> export const Chart = () => {
>   const chartData = [{...}];
>   const containerRef = useRef<HTMLDivElement>(null);
>   const [width, height] = useElementSize(containerRef);
> 
>   return (
>     <div ref={containerRef} style={{ width: "100%", overflow: "hidden" }}> // overflow: hidden is important
>       <LineChart
>         height={500}
>         width={width} // set the chart width to the width value returned from the hook
>         data={chartData}
>         margin={{
>           top: 5,
>           right: 30,
>           left: 20,
>           bottom: 5,
>         }}
>       >
>         <CartesianGrid strokeDasharray='3 3' />
>         <XAxis dataKey='key' />
>         <YAxis />
>         <Tooltip />
>         <Legend />
>         <Line
>           type='monotone'
>           dataKey='otherKey'
>           stroke='#2563eb'
>           activeDot={{ r: 8 }}
>         />
>       </LineChart>
>     </div>
>   );
> }
> ```
> 
> Hope this can help others who need their chart to be responsive!

This is amazing! Thank you so much, @andrewgarrison.

Hope AntD would implement the same in ResponsiveContainer.
This should not be closed, recurring to such hacks as described above is not acceptable.
Just to share another hack based on https://github.com/recharts/recharts/issues/1767#issuecomment-598607012 

(99% did not work for me, animation was really slow when resizing parent)

```tsx
import React from "react";
import { ResponsiveContainer } from "recharts";

interface MyChartProps {}

export const MyChart: React.FC<MyChartProps> =
  () => {
    return (
      <div
        sx={{
          width: "100%",
          height: "500px", // or whatever height you want OFC
          overflow: "hidden",
          position: "relative",
        }}
      >
        <div
          style={{
            width: "100%",
            height: "100%",
            position: "absolute",
            top: 0,
            left: 0,
          }}
        >
          <ResponsiveContainer width="100%" height="100%">
            {/* Chart content */}
          </ResponsiveContainer>
        </div>
      </div>
    );
  };
```
This is still an issue in 2022 and it is not giving me much confidence with the library.  
> 

this is sad, i have the same problem
First of all, I'm a big fan of this library, thank you! But I cannot understand, why is this issue is closed? For sure, it contains a number of workarounds, but still, it should be fixed inside the library itself. Could someone please help with re-opening this issue?
My Recommendation is just to stop using `ResponsiveContainer` and just use `AutoSizer` from `react-virtualized-auto-sizer` worked like a Charm for me at least

```
import AutoSizer from "react-virtualized-auto-sizer";

export default function Chart() {
  return (
    <AutoSizer>
      {({ width, height }) => <LineChart width={width} height={height}>{...}</LineChart>}
    </AutoSizer>
  );
}
```
Same issue over here.
> My Recommendation is just to stop using `ResponsiveContainer` and just use `AutoSizer` from `react-virtualized-auto-sizer` worked like a Charm for me at least
> 
> ```
> import AutoSizer from "react-virtualized-auto-sizer";
> 
> export default function Chart() {
>   return (
>     <AutoSizer>
>       {({ width, height }) => <LineChart width={width} height={height}>{...}</LineChart>}
>     </AutoSizer>
>   );
> }
> ```

This has finally fixed it for me after hours of trials and errors. Thank you @socramm9 ! 🙏
> My Recommendation is just to stop using `ResponsiveContainer` and just use `AutoSizer` from `react-virtualized-auto-sizer` worked like a Charm for me at least
> 
> ```
> import AutoSizer from "react-virtualized-auto-sizer";
> 
> export default function Chart() {
>   return (
>     <AutoSizer>
>       {({ width, height }) => <LineChart width={width} height={height}>{...}</LineChart>}
>     </AutoSizer>
>   );
> }
> ```

Works fine

[This](https://github.com/recharts/recharts/issues/172#issuecomment-523362671) worked for me!

Surprised that it is still an issue and I will be considering this issue when choosing chart libraries in the future. It's an issue that make dev's spend an unproportionate amount of time on something small
> I fixed it up using old lifehack with padding.
> 
> ```
> <div style={{position: 'relative', width: '100%', paddingBottom: '250px'}}>
>   <div
>     style={{
>       position: 'absolute',
>       left: 0,
>       right: 0,
>       bottom: 0,
>       top: 0,
>     }}
>   >
>     <ResponsiveContainer>
>       <YourChartGoesHere />
>     </ResponsiveContainer>
>   </div>
> </div>
> ```
> 
> paddingBottom value can be in px for fixed height, and in percents for aspect ratio.

it worked for me
This one worked for me, I was trying to use it inside the MUI Accordian. But this trick working fine on all the 3 major browsers - safari, chrome,firefox

```
<div style={{display: "flex"}}>
    <div  style={{ flex: 1, width: 0, height: 500 }}>
        <ResponsiveContainer>
            <RechartsAnyChart />
        </ResponsiveContainer>
     </div>
  </div>
```
This chart is good but still has a responsive issue 
This CSS work for me

.recharts-wrapper{
  width: 100% !important;
}

.recharts-surface{
  width: 100% !important;
  display: block;
}
Hi all, 

I re-opened this issue after recently becoming a maintainer of recharts and am trying to squash these bugs that are recurring issues for a lot of people. 

This thread is long and from what I can tell there are a lot of differences in the code since this issue was originally cut.
The original issue statement:
>however if you make the browser window smaller, the chart stays large.

is no longer true from what I can tell as of the latest version (2.4.0) - [codesandbox](https://codesandbox.io/s/area-chart-in-responsive-container-forked-mns9ty?file=/src/App.tsx)

But that is without flexbox - I'm assuming the issue with flexbox remains.

Can those that have commented on this issue chime in about what the current gripes are with `ResponsiveContainer`? As well as if any specific issues in this thread have been fixed? This will help me decide on next steps. Thanks!

A CodeSandbox repro of the issue as it stands today would be incredible

**Edit:** nvm repro here https://codesandbox.io/s/area-chart-in-responsive-repro-2023-u48m66
I haven't seen any answers suggesting the use of min-width: 0, but if you specify `min-width: 0` on your flex children then this issue is resolved (see commented out code in CSS file of above repro). This doesn't really seem hacky either - its just changing the default unwanted behavior of `min-width: auto`

That being said I'll probably make the same change internally so it works by default
Merged #3391 - this defaults min-width to 0 which overrides the default auto value. The original problem with not-shrinking when responsive container is a flex child should be solved. 

Will be released in next patch or minor release. Closing this issue back up. Thanks all!
Released in 2.5!
> My Recommendation is just to stop using `ResponsiveContainer` and just use `AutoSizer` from `react-virtualized-auto-sizer` worked like a Charm for me at least
> 
> ```
> import AutoSizer from "react-virtualized-auto-sizer";
> 
> export default function Chart() {
>   return (
>     <AutoSizer>
>       {({ width, height }) => <LineChart width={width} height={height}>{...}</LineChart>}
>     </AutoSizer>
>   );
> }
> ```

THANKS !! 🙏🏻
> 

Many thanks to you @SamuelPrigent  it worked very well for me too
Just changing from props of ResponsiveContainer  from width="100%" height="70%" to width="99%" height="70%" worked for me
issue is still there

my code is like

```
<div
          style={{
            display: "flex",
            flexDirection: "column",
          }}
        >
          <h6>
            Some text
          </h6>
          <div style={{ flexGrow: 1 }}>
               <ResponsiveContainer>
                      // chart here
              </ResponsiveContainer>
          </div>
        </div>
```

its not resizing and with width 99.9 and height 99.8 %, animation is very very slow
@ckifer It seems this is not fully solved. I also just stumbled into this again. 🤔  

I wonder whether we should even maintain our own ResponsiveContainer, if other solutions specialised to this problem are available, as mentioned above in https://github.com/recharts/recharts/issues/172#issuecomment-1725053568
Yeah I mean we're really just wrapping one of those solutions anyways right with resize detector. 

Most other chart solutions are just responsive out of the box iirc. While we could tell people to go use something else for responsive needs I think that downgrades the out of the box value recharts currently gives (even if this bug exists). 

Personally think we should keep responsive behavior but remove the extra component and have it as a part of each chart. If we need to change the internal implementation to get this to work that should be fine
(1) Our ResponsiveContainer wraps https://www.npmjs.com/package/react-resize-detector
Our way of usage is not the recommended way. We could upgrade the dependency and refactor to align with best practice. This could be a good first step either way. 

(2) In the README it says: 
> Container queries now work in [all major browsers](https://caniuse.com/css-container-queries). It's very likely you can resolve your problem using [pure CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries).
1. Sounds good
2. If we could get a css solution to work internally that would be huge - since container queries are like media queries I'm not sure how it replaces things but i guess investigation needed. 
Any updates on this? Would really love a fix

Responsive container has been refactored to use resize detector directly. That will be in the next minor release, but I haven't confirmed if that fixes this or not. Will check
@HHongSeungWoo do you know if your changes fix this?
@ckifer No, I think some changes might be needed for size detection in flexbox.
I'll create a PR, could you review it to see if there are any issues?
Yep
At v. 2.9, I was able to fix the no-shrink behaviour with the `width='99%'` hack, but charts with flex-basis assigned to them ignored it after the resize. 

However, with v. 2.10.3 of the library, I stopped experiencing the no-shrink behaviour, even in flexbox scenarios, so I highly recommend pulling the latest version to see whether the issue goes away. All my charts are rendered like this, if it matters:
```
<div
 className={cx(
    'chartCard p-6 gap-6 grow-[1] max-w-full',
    chartConfig.type === 'bar' ? 'basis-[37%]' : 'basis-[57%]',
 )}
>
<div className='h-[250px] overflow-x-auto'>
  <ResponsiveContainer debounce={2} width='100%' height='100%' minWidth={%depends on chart type%}>
    <Chart ... />
  </ResponsiveContainer>
</div>
</div>
```
Here's what ended up working for me, with two graphs at about 50% height each in a column. I needed the `flex-grow` for it to grow, and the `overflow: hidden` for it to shrink.
```jsx
<div
  style={{
    height: "95vh",
    display: "flex",
    flexDirection: "column",
  }}
>
  ...other content
  <div
    style={{
      flexGrow: 1,
      display: "flex",
      flexDirection: "column",
      overflowY: "hidden",
    }}
  >
    <div style={{ overflow: "hidden", flexBasis: "50%" }}>
      <ResponsiveContainer width="100%" height="100%">
        ...AreaChart
      </ResponsiveContainer>
    </div>
    <div style={{ overflow: "hidden", flexBasis: "50%" }}>
      <ResponsiveContainer>
        ...AreaChart
      </ResponsiveContainer>
    </div>
  </div>
</div>
```
In my case, `ResponsiveContainer` was inside a `ChartContainer`, and the `ChartContainer` had a fixed `height` and `width` set to 100%. I removed the `width` property on `ChartContainer`  and set `min-width: 100%`, then it worked 🤷‍♂️
ChartContainer is not a recharts component. Where is that coming from @heinsenberg82?
> ChartContainer is not a recharts component. Where is that coming from @heinsenberg82?

`ChartContainer` is a component from shadcn charts. You can see some examples on their website here: https://ui.shadcn.com/charts. They use recharts under the hood.
> > ChartContainer is not a recharts component. Where is that coming from @heinsenberg82?
> 
> `ChartContainer` is a component from shadcn charts. You can see some examples on their website here: https://ui.shadcn.com/charts. They use recharts under the hood.

@heinsenberg82 I did run into the same problem with shadcn charts. I did a little workaround which might help you. I added a parent container and tracked its width with [`react-resize-detector`](https://www.npmjs.com/package/react-resize-detector). The could below should give you an idea on how to do it. 

```jsx

const { height, width, ref } = useResizeDetector<any>({
    refreshRate: 500,
    refreshMode: "debounce",
  });

<div ref={ref} className="w-full h-full">
        <ChartContainer
          config={chartConfig}
          style={{ height: height || 1, width: width || 1 }}
        >
        { /* ... */ }
        </ChartContainer>
</div>
```
to anyone still facing this annoying issue, please use `display: grid` on the parent container. Example in TailwindCSS:

```
<div className="h-[400px] grid grid-cols-1">
  <ResponsiveContainer width="100%" height="100%">
    <AreaChart ...
  </ResponsiveContainer>
</div>
```
Hi everyone 👋 I am trying to reproduce this issue but cannot. Is there anything we can do better in the responsive container?
Okay I think I found



Patch:
diff --git a/src/component/ResponsiveContainer.tsx b/src/component/ResponsiveContainer.tsx
index 8c31e38b77..dc62133acc 100644
--- a/src/component/ResponsiveContainer.tsx
+++ b/src/component/ResponsiveContainer.tsx
@@ -167,10 +167,8 @@ export const ResponsiveContainer = forwardRef<HTMLDivElement, Props>(
           height: calculatedHeight,
           // calculate the actual size and override it.
           style: {
-            height: '100%',
-            width: '100%',
-            maxHeight: calculatedHeight,
-            maxWidth: calculatedWidth,
+            width: calculatedWidth,
+            height: calculatedHeight,
             // keep components style
             ...child.props.style,
           },
@@ -185,7 +183,17 @@ export const ResponsiveContainer = forwardRef<HTMLDivElement, Props>(
         style={{ ...style, width, height, minWidth, minHeight, maxHeight }}
         ref={containerRef}
       >
-        {chartContent}
+        {/*
+         * This zero-size, overflow-visible is required to allow the chart to shrink.
+         * Without it, the chart itself will fill the ResponsiveContainer, and while it allows the chart to grow,
+         * it would always keep the container at the size of the chart,
+         * and ResizeObserver would never fire.
+         * With this zero-size element, the chart itself never actually fills the container,
+         * it just so happens that it is visible because it overflows.
+         * I learned this trick from the `react-virtualized` library: https://github.com/bvaughn/react-virtualized-auto-sizer/blob/master/src/AutoSizer.ts
+         * See https://github.com/recharts/recharts/issues/172 and also https://github.com/bvaughn/react-virtualized/issues/68
+         */}
+        <div style={{ width: 0, height: 0, overflow: 'visible' }}>{chartContent}</div>
       </div>
     );
   },
diff --git a/storybook/stories/API/ResponsiveContainer.stories.tsx b/storybook/stories/API/ResponsiveContainer.stories.tsx
index e7d420b175..ef0ea8c7db 100644
--- a/storybook/stories/API/ResponsiveContainer.stories.tsx
+++ b/storybook/stories/API/ResponsiveContainer.stories.tsx
@@ -13,35 +13,48 @@ export default {
 };
 
 export const API: StoryObj<Props> = {
+  // https://github.com/recharts/recharts/issues/172
   render: (args: Args, context: RechartsStoryContext<Props>) => {
     return (
-      <ResponsiveContainer {...args}>
-        <AreaChart
-          width={500}
-          height={400}
-          data={pageData}
-          margin={{
-            top: 10,
-            right: 30,
-            left: 0,
-            bottom: 0,
-          }}
-        >
-          <CartesianGrid strokeDasharray="3 3" />
-          <XAxis dataKey="name" />
-          <YAxis />
-          <Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
-          <Tooltip />
-          <RechartsHookInspector
-            position={context.rechartsInspectorPosition}
-            setPosition={context.rechartsSetInspectorPosition}
-          />
-        </AreaChart>
-      </ResponsiveContainer>
+      <div
+        style={{
+          display: 'flex',
+          flexDirection: 'column',
+          width: '100%',
+          flexGrow: 1,
+        }}
+      >
+        <h6>Flexbox sibling</h6>
+        <div style={{ flexGrow: 1 }}>
+          <ResponsiveContainer {...args}>
+            <AreaChart
+              width={500}
+              height={400}
+              data={pageData}
+              margin={{
+                top: 10,
+                right: 30,
+                left: 0,
+                bottom: 0,
+              }}
+            >
+              <CartesianGrid strokeDasharray="3 3" />
+              <XAxis dataKey="name" />
+              <YAxis />
+              <Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
+              <Tooltip />
+              <RechartsHookInspector
+                position={context.rechartsInspectorPosition}
+                setPosition={context.rechartsSetInspectorPosition}
+              />
+            </AreaChart>
+          </ResponsiveContainer>
+        </div>
+      </div>
     );
   },
   args: {
-    width: '100%',
-    height: 400,
+    width: '80%',
+    height: '80%',
   },
 };


Test patch:
diff --git a/test/component/ResponsiveContainer.spec.tsx b/test/component/ResponsiveContainer.spec.tsx
index 0257a6fa02..ffc8d7e5d0 100644
--- a/test/component/ResponsiveContainer.spec.tsx
+++ b/test/component/ResponsiveContainer.spec.tsx
@@ -165,8 +165,10 @@ describe('<ResponsiveContainer />', () => {
       notifyResizeObserverChange([{ contentRect: { width: 100, height: 100 } }]);
     });
 
-    expect(element.firstElementChild).toHaveAttribute('width', '100');
-    expect(element.firstElementChild).toHaveAttribute('height', '200');
+    const testDiv = screen.getByTestId('inside');
+
+    expect(testDiv).toHaveAttribute('width', '100');
+    expect(testDiv).toHaveAttribute('height', '200');
   });
 
   it('should resize when debounced', () => {
@@ -189,8 +191,10 @@ describe('<ResponsiveContainer />', () => {
       notifyResizeObserverChange([{ contentRect: { width: 100, height: 100 } }]);
       vi.advanceTimersByTime(200);
     });
-    expect(element.firstElementChild).toHaveAttribute('width', '100');
-    expect(element.firstElementChild).toHaveAttribute('height', '200');
+    const testDiv = screen.getByTestId('inside');
+
+    expect(testDiv).toHaveAttribute('width', '100');
+    expect(testDiv).toHaveAttribute('height', '200');
   });
 
   it('should call onResize when ResizeObserver notifies one or many changes', () => {
@@ -210,8 +214,10 @@ describe('<ResponsiveContainer />', () => {
       notifyResizeObserverChange([{ contentRect: { width: 100, height: 100 } }]);
     });
 
-    expect(element.firstElementChild).toHaveAttribute('width', '100');
-    expect(element.firstElementChild).toHaveAttribute('height', '200');
+    const testDiv = screen.getByTestId('inside');
+
+    expect(testDiv).toHaveAttribute('width', '100');
+    expect(testDiv).toHaveAttribute('height', '200');
 
     expect(onResize).toHaveBeenCalledTimes(1);
 
@@ -303,10 +309,8 @@ describe('<ResponsiveContainer />', () => {
 
     expect(elementsInside).toHaveLength(4);
     expect(elementsInside[0]).toHaveStyle({
-      width: '100%',
-      height: '100%',
-      'max-width': '400px',
-      'max-height': '200px',
+      width: '400px',
+      height: '200px',
       'background-color': 'rgb(0, 0, 255)',
     });
     expect(elementsInside[0]).toHaveAttribute('height', '200');
@@ -314,10 +318,8 @@ describe('<ResponsiveContainer />', () => {
 
     // all elements are cloned with the same style props besides their own style
     expect(elementsInside[1]).toHaveStyle({
-      width: '100%',
-      height: '100%',
-      'max-width': '400px',
-      'max-height': '200px',
+      width: '400px',
+      height: '200px',
       'background-color': 'rgba(0, 0, 0, 0)',
     });
     expect(elementsInside[1]).toHaveAttribute('height', '200');