loading...
Cover image for How to Build a Simple Stacked Bar Chart with HTML & CSS in React

How to Build a Simple Stacked Bar Chart with HTML & CSS in React

stories_of_ren profile image ⚡️Ren⚡️ Updated on ・2 min read

How to build a Simple Stacked Bar Chart React Component from HTML and CSS!?!

In this post, we will build a stacked bar chart component in React while only using HTML <div> tags and CSS. This should be a fun little intro to data vis and the way we'll do this is by feeding data into our Bar Chart component and mapping through that data to create our chart. In the end, we'll have a chart like the one below.

Bar chart from HTML and CSS

The code below sets up our Bar Chart component as a functional component, deconstructing our props so we have easy access to our data. Our data is comprised of an array of objects, giving a percentage and a color. We will map through this data to create the different stacks of the bar chart.

Bar Chart Component:


const Bar = ({ data }) => {
    return (
        <div className="BarChart">
            // This is where we map through our data to create 
            // the different stacks of the bar chart, 
            // injecting the height and color via inline styling
            {data &&
                data.map((d) => {
                    return (
                        <div className="BarData" style={{ background: `${d.color}`, height: `${d.percent}%` }}>
                            <p className="PercentText">{d.percent + '%'}</p>
                        </div>
                    );
                })}
        </div>
    );
};

The rest is settled in the CSS. The container .BarChart accepts the height of its parent so that it will fill that constraint and has a width set so we can see the component.

:root {
    --color-primary: #2bc4bd;
    --color-primary-offWhite: #ebeded;
}


.BarChart {
    background-color: var(--color-primary);
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    height: inherit;
        // inherit will take in the height of its parent, you could also 
        // use 100% if the parent's height is set.
    width: 4em;
    overflow:hidden;
}

.BarData {
    display: flex;
    align-items: center;
    justify-content: center;
}

.PercentText {
    color: var(--color-primary-offWhite);
    font:700 1.25rem sans-serif;
    text-align: center; 
}

The most important of the CSS above is setting the Height and Width of the .BarChart. To help in the learning process, you can find the Pen below so you can play around with the code.

I hope this was a fun and helpful introduction to Data Vis. Thank you for taking the time to read even while so short! Please be on the lookout for more!

Thanks

Posted on by:

stories_of_ren profile

⚡️Ren⚡️

@stories_of_ren

Self taught Software Engineer. I have a preference for frontend.

Discussion

pic
Editor guide