Search code examples
reactjsrecharts

How do I add width to the bars in barchart. I am using recharts library with reactjs


In this code I have one sample json where I have provided name, value and width for the barchart.

import React from "react";
import { Bar, BarChart, ResponsiveContainer, Tooltip } from "recharts";

interface BarData {
  name: string;
  value: number;
  width: number;
}

const data: BarData[] = [
  {
    name: "Bar 1",
    value: 10,
    width: 100,
  },
  {
    name: "Bar 2",
    value: 20,
    width: 200,
  },
  {
    name: "Bar 3",
    value: 30,
    width: 300,
  },
];

const Barchart: React.FC = () => {
  return (
    <ResponsiveContainer height={400}>
      <BarChart data={data} layout="horizontal" barGap={10}>
        <Bar
          dataKey="value"
          width={(bar) => bar.width}
          fill="#5e5e5e"
          radius={[0, 0, 0, 0]}
        />
        <Tooltip />
      </BarChart>
    </ResponsiveContainer>
  );
};

export default Barchart;

ChatGPT provided me this code. But this doesn't work. If there is another way to add width to the bar then mention them.


Solution

  • You will have to use a custom shape for your Bar component.

    In your data, you add a new property, customWidth (it cannot be named as width as it will be overwritten by recharts.

    const data: BarData[] = [
      {
        name: "Bar 1",
        value: 10,
        customWidth: 100,
      },
      {
        name: "Bar 2",
        value: 20,
        customWidth: 200,
      },
      {
        name: "Bar 3",
        value: 30,
        customWidth: 300,
      },
    ];
    
    

    In your <Bar /> component, use the shape property to define a custom shape.

    For example

    <Bar
      dataKey="amount"
      isAnimationActive={false}
      onClick={(value) => console.log(value)}
      shape={(props) => (
        <CustomBar
          {...props}
          width={props.width}
          displayACH={displayACH}
          displayFailed={displayFailed}
          displayDisputed={displayDisputed}
        />
      )}
    />
    

    Then you create another custom bar component where you assign a new width

    function CustomBar(props) {
      console.log(props);
      return <Rectangle {...props} width={props.customWidth} />;
    }
    

    Here's an example stackblitz.