question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[xy-chart] Responsiveness is broken in some cases?

See original GitHub issue

I have responsiveness broken in my app, probably due to flex and grid positioning it somehow breaks it. But I’ll let you decide whom to blame.

Click to expand:
import React, { useEffect, useMemo } from 'react'
import {
  lightTheme as lt,
  darkTheme as dt,
  Grid,
  AreaSeries,
  Axis,
  XYChart,
  Tooltip,
  buildChartTheme,
} from '@visx/xychart'
import { ThemeConfig } from '@visx/xychart/lib/theme/buildChartTheme'
import { curveMonotoneX } from '@visx/curve'
import { LinearGradient } from '@visx/gradient'
import { Box, useColorMode, Stack, useBreakpointValue } from '@chakra-ui/react'
import { ParentSize } from '@visx/responsive'
import { css } from '@emotion/css'
import { MetricHistoryPoint } from '__generated__/graphql-types.generated'
import { formatMoney } from 'packlets/utils'

const dateScaleConfig = { type: 'band', paddingInner: 0.9 } as const
const moneyScaleConfig = { type: 'linear' } as const

const darkTheme = buildChartTheme(({
  ...dt,
  colors: ['#109CF1'],
} as unknown) as ThemeConfig)

const lightTheme = buildChartTheme(({
  ...lt,
  colors: ['#109CF1'],
} as unknown) as ThemeConfig)

const lineStyle = css`
  stroke-width: 3;
`

export const DashboardGraph = ({ data }: { data: MetricHistoryPoint[] }) => {
  const config = useMemo(
    () => ({
      x: dateScaleConfig,
      y: moneyScaleConfig,
    }),
    [],
  )
  const { colorMode } = useColorMode()
  const theme = colorMode === 'light' ? lightTheme : darkTheme

  useEffect(() => {
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent('scroll'))
    }, 300)
  })

  const xTicks = useBreakpointValue({ base: 3, xl: 5 })

  return (
    <ParentSize>
      {({ width }) => (
        <XYChart
          theme={theme}
          xScale={config.x}
          yScale={config.y}
          height={300}
          width={width - 16}
        >
          <LinearGradient
            id="area-gradient"
            from="#109CF1"
            to="#109CF1"
            toOpacity={0.1}
          />
          <Grid
            rows
            columns={false}
            strokeDasharray="10, 5"
            // @ts-expect-error
            strokeOpacity={0.3}
          />
          <AreaSeries
            dataKey="Cash in"
            data={data}
            fillOpacity={0.4}
            xAccessor={(it) => it.date}
            yAccessor={(it) => it.value}
            fill="url(#area-gradient)"
            stroke="url(#area-gradient)"
            lineProps={{
              className: lineStyle,
            }}
            curve={curveMonotoneX}
          />
          <Axis
            orientation="bottom"
            strokeWidth={0}
            numTicks={xTicks}
            hideAxisLine
            hideTicks
          />
          <Axis orientation="left" numTicks={5} hideAxisLine hideTicks />
          <Tooltip<{ date: string; value: number }>
            showVerticalCrosshair
            snapTooltipToDatumX
            snapTooltipToDatumY
            verticalCrosshairStyle={{
              strokeOpacity: 0.4,
            }}
            showSeriesGlyphs
            glyphStyle={{
              r: 4,
              fill: colorMode === 'light' ? 'white' : 'black',
              strokeWidth: 1.5,
              stroke: '#109CF1',
            }}
            renderTooltip={({ tooltipData }) => (
              <Stack borderRadius={4}>
                <Box>{tooltipData?.nearestDatum?.datum.date}</Box>
                <Box>{formatMoney(tooltipData?.nearestDatum?.datum.value ?? 0)}</Box>
              </Stack>
            )}
          />
        </XYChart>
      )}
    </ParentSize>
  )
}

In order to have my graphs to resize I have to deduct padding of the div that holds XYChart (I guess it’s div -> XY Chart generated div -> actual SVGs) So basically padding of the block that holds component above inside.

Here is how it looks when I add into XYChart width prop width - 16 Peek 2021-01-09 02-41

And here when I don’t add that or remove <ParentSize/> completely. I’m getting horizontal scrolling after page refresh and no resize. Note that the 2 graphs above are in regular display: flex, and 2x2 graphs at the bottom are in display: grid.

Peek 2021-01-09 02-43

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:3
  • Comments:7

github_iconTop GitHub Comments

3reactions
m-mujicacommented, Jul 11, 2022

Seems like the problem is caused by the automatic minimum size of flex item (I guess this also applies to grid items)

The “solution” to get the chart to resize when its parent shrinks is set min-width: 0 on the chart parent element.

Also, from the linked stack overflow response:

If you’re dealing with flex items on multiple levels of the HTML structure, it may be necessary to override the default min-width: auto / min-height: auto on items at higher levels.

In my case I had to set min-width: 0 in some parent flex items as well but it did the trick.

2reactions
mokicommented, Jun 29, 2021

@williaster having display: grid; or display: flex; anywhere up the parent chain set for the ParentSize component will break responsive behavior on shrink (smaller than initial render width).

One would be able to reproduce by adding:

body {
    display: grid | flex;
}

to the sandbox-styles.css inside the xychart demo

Preventable by rendering all of your chart stuff inside ScaleSVG component, but xychart simply uses svg. (I’ve found it out by making my own “xychart”)

Read more comments on GitHub >

github_iconTop Results From Across the Web

XYChart – amCharts 4 Documentation
Creates an XY chart, and any derivative chart, like Serial, Date-based, etc. ... In most cases it will mean the chart object. ......
Read more >
vx - Bountysource
I have responsiveness broken in my app, probably due to flex and grid positioning it somehow breaks it. But I'll let you decide...
Read more >
Broken Y Axis in an Excel Chart - Peltier Tech
Read why breaking axes is a bad idea, and get a tutorial in Panel Charts, ... I know everybody's case is special, and...
Read more >
21603 – Fundamental Chart features broken/missing
When creating a chart in Calc, the data groups are very restricted, making it completely impossible to use Charts in some cases. 1)...
Read more >
Perspective - Power Chart - Ignition User Manual 8.1
The Power Chart has a responsive design and a mobile-optimized ... Useful in cases where you want to display records from now to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found