Search code examples
reactjschartsreact-reduxrecharts

xAxis hides after resize in react rechart


I use react rechart library for creating a line chart. When I resize my browser window, the values or ticks in xAxis gets hidden. But I don't want the values in xAxis to get hidden. Kindly provide a solution to avoid the values in xAxis getting hidden.

My Line chart component code

import React from 'react'
import {
  LineChart, Line, XAxis, YAxis, ResponsiveContainer, CartesianGrid, Tooltip, Legend, ReferenceLine,
} from 'recharts';
import { lineChartXAxis, lineChartYAxis } from './chart.config';
// styles
import useStyles from "./styles";

const LineCharts = ({ dimensions, data, XAxisDataKey }) => {
    const {chartOuterWrap, chartInnerWrap} = useStyles()
    return ( 
        <div className={chartOuterWrap} style={dimensions}>
          <div className={chartInnerWrap}>
            <ResponsiveContainer>
              <LineChart height={'100%'} width={'100%'} data={data}>
                  <XAxis dataKey={XAxisDataKey}
                  tick={true}
                  interval={'preserveStartEnd'}
                  {...lineChartXAxis}
                  />
                  <YAxis
                  interval={0}
                  tick={true}
                  {...lineChartYAxis}
                   />
                  <Tooltip />
                  <Line type="monotone" strokeWidth={3} dataKey="uv" stroke="#24b32a" />
                  <Line type="monotone" strokeWidth={3} dataKey="pv" stroke="#fb8c00" />
                  <Line type="monotone" strokeWidth={3} dataKey="amt" stroke="#e53935" />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
    );
}

export default LineCharts;

I have also attached the image for easy understanding of the issue

enter image description here

After resizing the window

enter image description here


Solution

  • This is a known bug with Recharts, and the solution is to use customized tick marks:

    const CustomizedAxisTick = props => {
      const { x, y, payload } = props
    
      return (
        <g transform={\`translate(${x},${y})\`}>
          <text dy={16} textAnchor='middle' fill='#666'>{payload.value}</text>
        </g>
      )
    }
    

    Then in the chart types AreaChart, BarChart, LineChart, ComposedChart or ScatterChart, include the tick prop in the XAxis

    <XAxis tick={<CustomizedAxisTick />} />
    

    like this CustomizedLabelLineChart example. Experiment with settings in this codesandbox.