I have an array data structure that I passed to the Recharts BarChart component. All values dataX for each name would be stacked into the same bar, and I want to show the total amount at the end of the bar.
const data = [
{
name: 'nameA',
data1: 30,
data2: 30,
total: 60,
},
// ...
];
The way I'm rendering the bars:
const valueAccessor = (item) => (item ? item.total : 0);
const renderBars = () => {
return parsedData.map(({name, dataKey, barName, color, renderShape}) => {
<Bar
key={`axis-${name}-${dataKey}`}
dataKey={dataKey}
stackId={barName}
fill={color}
shape={renderShape}
>
<LabelList valueAccessor={valueAccessor(barName)} position="right" />
</Bar>
});
}
I have different ways of rendering them with colors and probably would not need another data structure (see that renderBars uses parsedData instead of data, but that's something extra that I need to work on).
The output is this:
As you can see, the numbers are kind of bold, and by inspecting them, I see that I can just remove the element and the number is still there, as 3 numbers are being rendered instead of 1. (because I have 3 stacked bars).
Is there any way of making recharts render just one label per row, instead of per stacked bar?
Thanks!
After messing a little with the library, I found out that is inevitable to render 1 label when having 3 bars stacked per row/column. The only way of rendering a label is by setting the LabelList component as a child of a Bar component.
And if you have 2 bars, then you render a label for the first stacked bar, and then you don't render a label for the second stacked bar, in my case the label ended up not being rendered at all. So my only solution would be just to render a LabelList for the last stacked bar per row/column.
In the previous case, when having 3 stacked bars per row/column:
const GROUPS = 3;
const valueAccessor = (item) => (item ? item.total : 0);
const renderBars = () => {
return parsedData.map(({name, dataKey, barName, color, renderShape}) => {
<Bar
key={`axis-${name}-${dataKey}`}
dataKey={dataKey}
stackId={barName}
fill={color}
shape={renderShape}
>
{index % (parsedData.length / GROUPS) === (parsedData.length / GROUPS - 1) &&
<LabelList valueAccessor={valueAccessor(barName)} position="right" />}
</Bar>
});
}
The same output only has 1 number per row (you can see the numbers are not "bold")