How To Build A Bar Graph With React

Today I would like to show you how to go about building a simple bar graph with React. We will start off by defining what components we want to create, and then build out the basic HTML/CSS/JSX structure for them. Next, we will dive into some more intermediate React concepts, where we will make our components quite literally, “react”, to the data that is fed to them.

I aim to be highly detailed in my approach, but also respectful of your time. Therefore, I will try to keep this article within a reasonable length, and may omit small unimportant details throughout.

I highly advise anyone reading this to maintain a big picture perspective, and not to get bogged down by syntax that confuses you. If you are having trouble wrapping your head around some logic, please just skip it. I am a big believer that a big picture mindset is imperative when reading tutorials like this. If it continues to bug you, please post a question in the comments section, and I will gladly answer it.

The full working version of this tutorial is available via this Codepen for you to refer to throughout the tutorial and to do with as you please.

Planning Our Graph Components

I’d like for you to take a look at the picture below and imagine for a few minutes how you might break this graph down into small, separate pieces of UI. What pieces added together make up the final result we see below? How can we separate them in a way that is easily understandable, and also highly maintainable from a code perspective? Answering these questions is essential to successfully building out user interfaces with a component based model.

What our finished bar graph will look similar to.

Hopefully after taking a few minutes like I suggested above, you came up with a few ideas of how to break our graph down into smaller subsections of functionality. I also came up with a few ideas of my own. Here is what I am suggesting for our component structure.

  • Graph (Top level parent component).
  • BarTextContent (This will handle displaying the names of the cryptocurrencies on the left hand side of the graph).
  • Bar (Displays a single bar on the screen)
  • Line (Displays a single vertical line on the screen)
  • Marker (Displays a single number below a Line component on the bottom of the graph).

I would like to stress that there is no 100% right way when it comes out to building React Components. Do what feels right, as long as your code is readable and can easily be refactored or built upon in the future.

Building The React Scaffold

Typically, any React Component that you build will live inside of an application. Therefore, we are going to start off by creating an App Component that we are going to connect to the DOM.

Create the App scaffold and create an entry point to the DOM

This simple code ensures that whatever lives inside of the App component has the ability to render itself into a real HTML page where it can be visible to the user.

Building Graph

In order to start working on Graph, we need to think about what type of React Component we want to create it as. Seeing as Graph is our top level component, and that it encapsulates a lot of functionality inside of it, I am going to suggest creating it as a class based React Component. The reason for my choice is that it is highly probable that in the future we may want to add additional functionality to our Graph. Having Graph already built as a class based component makes it easier to add state and/or methods to extend its functionality.

This will be the only other class based component we make in this tutorial. Everything else will be functional components, or “dumb components”, whose sole job is to display something to the screen.

Here is what we will start off with:

Notice how I give the top level div a className of “graph-wrapper”. This will be more apparent why I did this towards the end of the tutorial, when we put the finishing touches on Graph. For now, just focus on the div inside of it with className of “graph”.

P.S. Starting from here, I will be referring to divs by their classNames via CSS syntax to cut down on unnecessary verbiage. For example, I will refer to a div with a className of “pizza” as .pizza

Sorry to disappoint, but there is no pizza being served with this tutorial.

Beginning CSS Styling For Graph

Reviewing our Graph photo again, it seems to me that we should start off by creating a div with some width, height, and a grey background.

Reviewing our Bar Graph For CSS purposes.
Assigning height, width and background CSS for .graph

In order to make this change viewable in the HTML document we need to place Graph inside of App via our React code. App is currently hooked up to the DOM, but is not showing anything because we have not put any content inside of it. Here is how we do that:

Rendering Graph to the DOM so we can work on it.

This is what we now have rendered to the HTML preview on Codepen:

Graph is now just a grey box.

This is a great start. To keep things going smoothly, I think we should move onto something simple. Adding our vertical lines to Graph seems like a perfect fit for that.

Creating The Line Component

The Line component’s job is super simple: display a vertical line to the screen. Here is what we are going to start the Line component off as:

Line Component Skeleton

Now let’s create a little CSS for it:

Line Component CSS

With this in place, let’s place Line into Graph and see what the result will be.

Placing Line into Graph Component

Producing a vertical Line inside the React Graph Component

Let’s copy and paste a few more Line Components inside of Graph, but instead of keeping all the Line components left positioning at 10%, we are going to override that specific styling property. This will prevent the lines from stacking on top of each-other.

In order to do this we need to pass down a prop to our Line component. For this specific prop, we want it to be a number that represents how far left we want the Line to appear.

Here is what we can do:

Passing props to Line Component
Dynamic left positioning inside Line Component

With that in place, we get this as a result:

Multiple Vertical Lines Inside Graph Component

I am pretty confident that this is going to work for us now. To finish this off we should build a method inside of Graph that renders all of these lines dynamically for us. Once that is built we can forget about the vertical lines, and move on to bigger and better things.

Dynamically Rendering Multiple Lines

Moving the logic to a method to render the Line components for us automatically is a far better solution than copy and pasting multiple Line components inside of Graph.

Creating a renderLines method in the Graph Component

What this method does is use some fancy ES6 to create a basically a useless array(in regards to it containing any data) with length of 10 that we can map over. We use the second argument of map to easily pass an auto-incremented number into each Line component via props. I’m not 100% in love with the syntax that is needed to do this, but in my opinion, I think it beats having to write for loops. Notice how I multiply each iteration of i by 10. This ensures we pass down an integer like 0, 10, 20, 30 etc.

This is what our method produces to the HTML Document:

Displaying the vertical lines to the screen is now complete. Our next plan of attack is going to be displaying creating the BarTextContent component that lives on the left hand side of Graph.

Building The BarTextContent Component

So this is where things get a little interesting CSS wise. Currently we have .graph that handles the width, height, and background color of Graph. However, in order to achieve the layout we want, we need things to be laid out in the manner depicted below.

To achieve this, I have restyled .graph to have display: flex in my CSS. Also I am going to move a few things around inside of Graph.

Heres what BarTextContent looks like for now as a component:

Setting .graph to display: flex now means that BarTextContent and .bar-lines-container are going to sit side by side. We need to write some additional CSS to make sure both of these divs take up a specific width of the surrounding .graph div, as well as make sure they both take up 100% of its height. Here is the CSS for that:

Notice how I added two random background colors on these divs. I did this temporarily to show what exactly is going on in our component. The picture below shows what is currently happening:

Looking closely, we can see that there is a bit of an overlap with one of the vertical lines overflowing into BarTextContent’s area. This is occurring because the vertical lines are set to an absolute position. An absolutely positioned element relies on a parent with position: relative to calculate where it should be placed. Seeing as .graph is the only div with position: relative set, The lines are trying to place themselves in relation to that div. This is easily fixed by adding adding a position: relative styling to .bar-lines-container.

P.S. I won’t be showing the CSS for this. Also, please be aware that I will be removing the temporary background colors, and removing the gray background color from .graph, and giving .bar-lines-container that background color instead. Reason being, is that we don’t want BarTextContent to have a grey background, we want it to have no background.

Let’s leave BarTextContent for now, and create the Bar component. We will hop back after that to finish this up component up.

Creating The Bar Component

To expedite things a little bit, I have created the Bar component with the props I think it needs to be dynamic. I also created some CSS for it.

Bar is going to receive a percent prop that will tell it how much width it should set itself to inside of .bar-lines-container. Let’s place a few Bar components inside Graph and see what happens.

Voila! I think this is going to work for us. I am going to remove these Bars for now. This is where all the fun JavaScript begins!

Feeding Data Into Our Graph

As I mentioned at the start, we are going to be feeding data on six cryptocurrencies into our Graph. Here is what the data set looks like.

We are going to put the currencies array into state inside of the App component, and pass it down as a prop named currencies to Graph. If you need to see how I do this, just refer to the App component in the Codepen as we continue.

Displaying The Bars Based On The Data We Received

Assuming we now have access to a prop called currencies inside of Graph, we are going to build out a method inside of Graph that takes care of displaying the Bars based on the received data. The calculation we are going to perform isn’t really meaningful if you were a serious finance person, but I am not here to teach you about market capitalization or finance, I am here to show you how to utilize React.

Here is what I am going to propose our method does:

  • Calculates the sum of all of the cryptocurrencies marketCap value.
  • Map through the currencies array, and for each iteration produce a Bar Component.
  • Returns an array of Bar Components to be displayed on the screen

Here is my shot at it:

Placing a call to { this.renderBars() } right below where we invoke the renderLines method should now produce something like this for us:

Now let’s get the text to show up next to each Bar on the left hand side.

Displaying Text in BarTextContent

In order to dynamically render text inside of BarTextContent we need to pass down the currencies array as props to it. In Graph I am going to create this prop on BarTextContent. Also, Here is my refactor of BarTextContent:

If everything went according to plan, we should get a result like this.

Your Challenge

If I keep writing tutorials like this, I am always going to end them by presenting you with a challenge. If you are a keen observer(which I think you are), you will notice that I did not include how to create the Markers at the bottom of the Graph. My challenge for you is to figure out how you would create and display these Markers.

The full working version at this Codepen has this included for you to reference.

Good Luck!