akshay23codes
akshay23codes

Reputation: 39

recharts line chart not responsive inside a responsive container

<div>
    <ResponsiveContainer width="99%" height={400}>
      <LineChart
        data={data}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line
          type="monotone"
          dataKey="pv"
          stroke="#8884d8"
          activeDot={{ r: 8 }}
        />
        <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
      </LineChart>
    </ResponsiveContainer>
  </div>

Rechart on desktop:

Rechart on desktop

Rechart when window is resized: Rechart when window is resized

Line chart is not responsive until I reload the page again,

Rechart when window is reloaded: Rechart when window is reloaded

same things happen otherway around.

please see images to understand question clearly.

Upvotes: 0

Views: 4372

Answers (4)

John Paolo Bautista
John Paolo Bautista

Reputation: 33

I think this is a bug.

what you can do is set ResponsiveContainer width to 99%

<ResponsiveContainer width="99%" height="100%">
     <chart here..../>
</ResponsiveContainer>

Upvotes: 2

Areej Aljeraiwi
Areej Aljeraiwi

Reputation: 9

  1. create new class

import { useState, useEffect } from "react" const useDeviceSize = () => {

const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)

const handleWindowResize = () => {
  setWidth(window.innerWidth);
  setHeight(window.innerHeight);
}

useEffect(() => {
  // component is mounted and window is available
  handleWindowResize();
  window.addEventListener('resize', handleWindowResize);
  // unsubscribe from the event on component unmount
  return () => window.removeEventListener('resize', handleWindowResize);
}, []);

return [width, height]

}

export default useDeviceSize

  1. import the new class in your chart class
  2. put in your chart class

const [width, height] = useDeviceSize();

  1. remove ResponsiveContainer tag
  2. LineChart width={width/1.6}
  3. note : 1.6 you can change it to what you see is suitable

Upvotes: 1

Paritosh
Paritosh

Reputation: 11

remove ResponsiveContainer tags and try < LineChart width={window.screen.width} />

Upvotes: 0

grenzbotin
grenzbotin

Reputation: 2565

This is an known issue in current recharts version 2.1.0: https://github.com/recharts/recharts/issues/2620

You can downgrade to version 2.0.10 and the responsiveness will work again.

Upvotes: 0

Related Questions