14

I'm trying to create a custom collapsable legend for my data visualization app. It uses react and recharts. the component renders nicely the first time. But when I collapse the legend and reopen it, the responsive container doesn't shrink to fit. This would be easier if I knew the size of the parent container in pixels but I don't have that information on render. Is this a bug with recharts or flex box or am I doing it wrong?

Heres the code: https://codesandbox.io/s/8krz9qjk52

Clarification: The problem is that when I close and then open the legend, the legend component gets pushed out of the viewing area and the chart does not shrink back to the original smaller size.

Lucas D
  • 460
  • 1
  • 4
  • 15

6 Answers6

41

It seems rather hacky but a viable fix is to set width to 99% with a height or aspect ratio.

<ResponsiveContainer width="99%" aspect={3}>

See this issue:

https://github.com/recharts/recharts/issues/172

atomictom
  • 1,637
  • 16
  • 14
10

I know this is a really old issue, but I'm posting here just in case somebody else lands here via Google.

I don't know why this works, but setting position: absolute on .recharts-wrapper will fix this issue entirely. So far I have found no downsides to this, but YRMV.

trenternet
  • 101
  • 1
  • 2
  • I am having this issue and can't figure out how to fix it using any of the google'd issues including this one. Anyone else have fixes? – dsldsl Jun 10 '22 at 05:34
5

try this, it resolved the responsiveness (resizing) for both width and height

<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>
wavefly
  • 147
  • 2
  • 5
  • can you please check again if this works without any error mesaage ERROR: { "message": "Uncaught SyntaxError: Unexpected token '<'", "filename": "https://stacksnippets.net/js", "lineno": 12, "colno": 9 } – Sumathi J Feb 15 '23 at 10:12
2

The Best bet is to give it a width of 100% then play around with the aspect ratio till if satisfys you. I did this to adapt to different screen sizes

const theme = useTheme(); //this is from mui
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

<ResponsiveContainer width="100%" aspect={isMobile?1.5:1.8}>

Works like a charm

louis
  • 422
  • 1
  • 4
  • 14
1

Since I'm having similar problems in my project, I decided to stick with this question. I was finally able to get a working solution!

codesandbox

I'll list the changes I made from biggest to smallest:

I lifted state up from CustomLegend to CustomChart.

  • Now, CustomChart is in charge of what happens. It passes visibility information to CustomLegend as a prop. How does CustomChart know when to change state?

  • CustomChart has a member function called handleButtonClick that sets its state. handleButtonClick is sent to CustomLegend as a prop. So CustomChart renders CustomLegend like this:

    <CustomLegend
        items={legendData}
        onClick={this.handleButtonClick}
        legendVisible={this.state.legendVisible}
    />
    

    Now in CustomLegend, we can include this in the button definition: onClick={this.props.onClick} Note that this pattern only works if the original function is bound to the parent since it alters the parent's state.

chart-container is now a CSS Grid container.

  • It renders an inline style handling the column width based on state.

    <div
        className="chart-container"
        style={{
          gridTemplateColumns: this.state.legendVisible
            ? "80% 1fr"
            : "1fr min-content"
        }}
    >
    

    Note that 1fr is a fractional unit which, in this case, serves to fill the remaining space.

  • In styles.css, grid-auto-flow is set to column which allows things to be placed in the grid as columns. The things we place into the grid are SampleChart and CustomLegend, so SampleChart is the left column and CustomLegend is the right column.
  • gridTemplateColumns: 80% 1fr: When the legend is visible, we want the left column to take up 80% of the width and the right column to fill the rest.
  • gridTemplateColumns: 1fr min-content: When the legend is invisible, we want the right column to take up the minimum amount of space which its elements fill and the left column to fill the remaining space.

CustomLegend has only a single render method.

  • Instead of renderVisible and renderHidden, there is one method which conditionally renders the legend-list based on props (dependent on CustomChart's state).
  • The legend-container always renders now (it is a grid item).

Other small changes:

  • In SampleChart: <ResponsiveContainer width="100%" height="100%" className={props.className}> This has been changed because <SampleChart className="chart-area" data={data} /> actually sends className as a prop. Be careful with this! You need to set className directly on the parent tag in SampleChart's returned hierarchy (in this case the ResponsiveContainer). Try going back to your original codesandbox and changing the background-color on chart-area in styles.css (nothing happens!).
  • overflow: scroll in all instances from styles.css because we no longer need it.

You'll notice that if you attempt a grid layout using only fr units or any flex layout on chart-container, that the chart doesn't resize properly. Unfortunately, Recharts' ResponsiveContainers just don't play nicely with Grid or Flexbox (the project's main contributors are gradually tapering off support – no commits in 3 months as of now).

Parabolord
  • 302
  • 3
  • 13
0

Add the following to your styles.css:

html, body, #root {
  width: 100%;
  height: 100%;
}

otherwise .chart-container, even though its width and height are set to 100%, will not take up the entire viewport. Then in SampleChart.jsx, change this:

<ResponsiveContainer width="100%" height={400}>

to this:

<ResponsiveContainer width="100%" height="100%">

to make your ResponsiveContainer's height... well, responsive.

Parabolord
  • 302
  • 3
  • 13
  • that doest help. When I close and then open the legend, the legend component get pushed out of the viewing area and the chart does not shrink back to the original smaller size – Lucas D Jun 16 '18 at 21:51
  • Sorry, I misinterpreted the question. Check out my second answer! – Parabolord Jun 20 '18 at 19:22