The react-horizontal-stacked-bar-chart library lets us add a bar chart easily in our React app.
In this article, we’ll look at how to use it to add a stacked bar chart to our React app.
Installation
We can install the library by running:
npm i react-horizontal-stacked-bar-chart
Simple Chart
After we installed the package, we write:
import React from "react";
import HSBar from "react-horizontal-stacked-bar-chart";
export default function App() {
return (
<div className="App">
<HSBar data={[{ value: 10 }, { value: 20 }]} />
</div>
);
}
to add 2 bars stacked together with the HSBar
component.
There is nothing else displayed except the bars.
Complete Chart
To add a complete chart with the labels, we write:
import React from "react";
import HSBar from "react-horizontal-stacked-bar-chart";
export default function App() {
return (
<div className="App">
<HSBar
height={50}
showTextIn
showTextUp
showTextDown
outlineWidth={0.5}
outlineColor="black"
id="chart"
fontColor="rgb(50,20,100)"
data={[
{
name: "Owed",
value: 80,
description: "$80,00",
color: "red"
},
{
name: "Paid",
value: 200,
description: "$200,00",
color: "lightgreen"
}
]}
onClick={(e) => console.log(e.bar)}
/>
</div>
);
}
The showTextIn
prop shows text inside the bars.
showTextUp
shows the label text above the bars.
showTextDown
shows the label text below the bars.
outlineWidth
has the width of the border.
outlineColor
has the color of the border.
fontColor
has the font color.
data
has the data for the stacked bars.
The name
has the name that is displayed in the labels.
value
has the length of the bar.
description
has the description shown before the name
.
color
has the color of the bar.
onClick
is a function that’s called when the bar is clicked.
A single bar would be displayed with the bars with thedata
array stacked together.
Conclusion
The react-horizontal-stacked-bar-chart library lets us add a stacked bar chart within a React app with a single bar.