•  


ResponsiveContainer does not respond to resizing from large to small · Issue #172 · recharts/recharts · GitHub
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ResponsiveContainer does not respond to resizing from large to small #172

Open
marchaos opened this issue Aug 15, 2016 · 68 comments
Open
Assignees
Labels
bug General bug label P0 Critical priority issues

Comments

@marchaos
Copy link

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.

@xile611
Copy link
Member

@marchaos It works fine in this demo . Can you show your question in an online jsfiddle demo ?

@marchaos
Copy link
Author

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.

@xile611
Copy link
Member

@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.

@marchaos
Copy link
Author

@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.

@xile611
Copy link
Member

xile611 commented Aug 16, 2016

@marchaos It seems to be the problem of calculation strategy for flex box. You can check this stackoverflow question for detail.

@marchaos
Copy link
Author

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

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

@mrwillis
Copy link

mrwillis commented Jun 12, 2017

Does anyone know the fix for flexDirection: 'column'? Apparently setting width: 0 does not fix the issue here.

@mrwillis
Copy link

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/ , it should, but it doesn't.

@viztor
Copy link
Contributor

This problem seems to persist.

@gennaroanesi
Copy link

got it working with a 99% width and a fixed height

@akuji1993
Copy link

We also got it working using 99% width.

@nicholasmaddren
Copy link

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.

@ghost
Copy link

ghost commented Jun 7, 2019

Issue is still there.

Any suggestions?

@tmercado
Copy link

@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.

<
div
 style
=
{
{
 height
: 
'1000px'
,
 width
: 
'1000px'
 }
}
 >

    <
div
 style
=
{
{
 height
: 
'100%'
,
 width
: 
'60%'
 }
}
>

          <
ResponsiveContainer
 height
=
{
/*some percent*/
}
 width
=
{
/*some percent*/
}
>

          <
/
ResponsiveContainer
>

     <
/
div
>

<
/
div
>

@ghost
Copy link

Thanks @tmercado !

I decided to switch to Charts.js to avoid this issue for future projects.

@wouterds
Copy link

wouterds commented Jul 12, 2019

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

@mixail-novikov
Copy link

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.

@olelivalife
Copy link

Animations are very slow with width 99%

@akuji1993
Copy link

@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

@G07cha
Copy link
Contributor

For me, setting overflow: hidden in parent component solves the problem.

<
div
 style
=
{
{
 overflow
: 
'hidden'
,
 'flex-basis'
: 
"50%"
 }
}
>

  <
ResponsiveContainer
>

    <
YourChartGoesHere
 /
>

  <
/
ResponsiveContainer
>

<
/
div
>

@vitalbadjo
Copy link

new hack for issue
set position: relstive for .recharts-surface

.recharts-surface {
  position: absolute !important;
  left: 0px;
  top: 0;
}

@bmitchinson
Copy link

bmitchinson commented Apr 29, 2020

.recharts-surface {
position: absolute !important;
left: 0px;
top: 0;
}

@VitaliyZH
relative ? or absolute . Your snippet shows aboslute?

@ShamansCoding
Copy link

ShamansCoding commented May 25, 2020

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:

<
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.

@christiaanwesterbeek

Animations are very slow with width 99%

Yep, I had that too. But then I tried the solution right before your comment; the one by @mixail-novikov . It works flawlessly.

@just-Bri
Copy link

just-Bri commented Dec 1, 2020

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.

@christiaanwesterbeek
Copy link

christiaanwesterbeek commented Dec 1, 2020

@reifnotreef Let us know why the one by @mixail-novikov is not working for you. It is working for me flawlessly.

@just-Bri
Copy link

@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.

@raj-altrio
Copy link

This should definitely not be closed. Changing the height of the container does not trigger a change in height for the chart.

@ckifer
Copy link
Member

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!

@ckifer
Copy link
Member

Released in 2.5!

@SamuelPrigent
Copy link

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 !! ????

@Kimbohlovette
Copy link

Many thanks to you @SamuelPrigent it worked very well for me too

@NikolyCover
Copy link

Just changing from props of ResponsiveContainer from width="100%" height="70%" to width="99%" height="70%" worked for me

spiltbeans added a commit to spiltbeans/paa-invoicing that referenced this issue Jun 21, 2023
features:
- there was a problem when the ControllerSpace.tsx expanded the GraphSpace.tsx wouldn't shrink. fixed by having the graph space wrapper have flex-1 and for the width of the ResponsiveContainer be 100%->99%
- overflow question of issue ^ : (
https://stackoverflow.com/questions/50891591/recharts-responsive-container-does-not-resize-correctly-in-flexbox
)
- git issue of issue ^ : (
recharts/recharts#172
)
- added IDs for html elements. it's easier to debug
- changed ControllerSpace.tsx collapse design to switch between a bordered controller to an expand button
- moved the sheet selector, sheet upload button, and sheet upload modal Dashboard.tsx -> GraphPanel.tsx
@mayurwankhade96
Copy link

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

@nikolasrieble
Copy link
Contributor

nikolasrieble commented Oct 14, 2023

@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 #172 (comment)

@ckifer
Copy link
Member

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

@nikolasrieble
Copy link
Contributor

(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 . It's very likely you can resolve your problem using pure CSS .

@ckifer
Copy link
Member

  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.

@DarrenBaldwin07
Copy link

Any updates on this? Would really love a fix

@ckifer
Copy link
Member

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

@ckifer
Copy link
Member

@HHongSeungWoo do you know if your changes fix this?

@HHongSeungWoo
Copy link
Member

@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?

@ckifer
Copy link
Member

Yep

@HHongSeungWoo HHongSeungWoo mentioned this issue Oct 27, 2023
9 tasks
@ckifer ckifer reopened this Oct 30, 2023
GMer78 pushed a commit to GMer78/recharts-1 that referenced this issue Nov 24, 2023
<!--- Provide a general summary of your changes in the Title above -->

## Description

I have fixed issue 
recharts#172


## Related Issue

recharts#172


## Motivation and Context

<!--- Why is this change required? What problem does it solve? -->

## How Has This Been Tested?

<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran
to -->
<!--- see how your change affects other areas of the code, etc. -->

## Screenshots (if appropriate):

## Types of changes

<!--- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)

## Checklist:

<!--- Go over all the following points, and put an `x` in all the boxes
that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're
here to help! -->

- [x] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have added tests to cover my changes.
- [x] I have added a storybook story or extended an existing story to
show my changes
- [x] All new and existing tests passed.
@max-petrenko
Copy link

max-petrenko commented Dec 13, 2023

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>

@phoenixeliot
Copy link

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.

<
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
>

Sign up for free to join this conversation on GitHub . Already have an account? Sign in to comment
Labels
bug General bug label P0 Critical priority issues
Projects
None yet
Development

No branches or pull requests

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본