Wrap any chart in a ResponsiveContainer component. We should expect the chart to be responsive. The chart's dimensions are static and do not change when resizing the window. We are using Recharts v2.7.2 with React 18.2.0.
Not even the examples are fully responsive:
The examples work only when the wrapper div is side by side with the editor div. When I resize and the wrapped div goes above the editor div, the chart is no longer responsive and defaults to 800px width.
I have tried the following combinations, but nothing works. The chart inside is always the same:
<BarChart
with={500}
height={300}
data={data}
margin={{
top: 20,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="pv" stackId="a" fill="#8884d8" />
<Bar dataKey="amt" stackId="a" fill="#82ca9d" />
<Bar dataKey="uv" fill="#ffc658" />
</BarChart>
The following is not responsive:
function App() {
return (
<div style={{ width: "1000px", height: "1000px" }}>
<ResponsiveContainer width={"100%"} height={"100%"}>
// <ResponsiveContainer width={"100%"} height={300}>// same behavior = not responsive
<BarChart> ... </BarChart>
</ResponsiveContainer>
</div>
);
}
The following does not render anything:
function App() {
return (
<div style={{ width: "100%", height: 300 }}>
<ResponsiveContainer>
// <ResponsiveContainer width={"100%"} height={"100%"}> // same behavior = no render
// <ResponsiveContainer width={"100%"} height={300}>// same behavior = no render
<BarChart> ... </BarChart>
</ResponsiveContainer>
</div>
);
}
The following is not responsive:
function App() {
return (
<div style={{ width: "1000px", height: "1000px" }}>
<div style={{ width: "100%", height: "100%" }}>
<ResponsiveContainer>
// <ResponsiveContainer width={"100%"} height={"100%"}> // same behavior = not responsive
// <ResponsiveContainer width={"100%"} height={300}>// same behavior = not responsive
<BarChart> ... </BarChart>
</ResponsiveContainer>
</div>
</div>
);
}
In the CodeSandbox example, if you comment <div style={{ width: "1000px" }}>
then the div becomes responsive, but it is responsive only on CodeSandbox. In my project, the chart is never responsive, no matter what I try.
change wrapping div width with max-width to get the responsiveness:
<div style={{ maxWidth: 1000, height: 300 }}>
<ResponsiveContainer width={"100%"} height={"100%"}>
</div>