How to set the height and width for responsive chart using React Recharts?

Sometimes, we want to set the height and width for responsive chart using React Recharts.

In this article, we’ll look at how to set the height and width for responsive chart using React Recharts.

How to set the height and width for responsive chart using React Recharts?

To set the height and width for responsive chart using React Recharts, we can wrap our bar chart with the ResponsiveContainer component.

For instance, we write:

import * as React from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from "recharts";

const data = [
  { name: "Page A", uv: 400 },
  { name: "Page A", uv: 300 },
  { name: "Page A", uv: 600 }
];

export default function App() {
  return (
    <ResponsiveContainer width="95%" height={400}>
      <BarChart
        className="barChart"
        width={600}
        height={300}
        data={data}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
        label="heaf"
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="uv" barSize={10} fill="#05386b" />
      </BarChart>
    </ResponsiveContainer>
  );
}

We wrap the BarChart with the ResponsiveContainer to set the BarChart‘s width and height.

And we set the width and height with the width and height props.

We add the BarChart component to render a bar chart.

The data prop has the bar chart data.

The bars are added with the Bar component with the dataKey prop set to the property name of the items in the data array as the value.

To change the bar color, we set the fill prop to the value we want.

We set the margin prop to set the margins of the bar chart.

CartesianGrid adds a grid in the background. XAxis and YAxis adds the x and y axes respectively.

Conclusion

To set the height and width for responsive chart using React Recharts, we can wrap our bar chart with the ResponsiveContainer component.