React: Learn all the Major Concepts by Building a Shopping List App Part 1

React is a Javascript library for building user-interfaces. It’s used by a lot of companies like Netflix, Coursera, Airbnb and many more. Originally developed and open-sourced by Facebook. It’s currently maintained by Facebook and a community of open-source software developers.  One thing to take note here is that React is not a framework. It is a library. It does not provide a complete solution. We will need to combine other libraries along with React to form a complete solution to a specific problem. These other libraries along with React forms what is known as the React ecosystem.

If we take a look at the latest Stackoverflow survey, React sits pretty comfortably at the number third spot as the most used technology among developers. Here is a screenshot for reference

The same survey also lists React as the second most loved technology to work with. Here is another screenshot of the same-

React is gaining a lot of popularity and the community is pretty active which means that it is much easier to get help when we get stuck on a particular issue. This blog post’s objective is to explain the core concepts of React by building a sample application. I think that explaining the concepts as we build this application will be far more helpful rather than just glossing over each of them with a small code sample. In the end we will have a nice application and we will even get the better picture of how to code in React. So two things at one go sounds good to you? Read on..

Thinking in React

One of the first things to understand in React is the component. Think of component as a collection of HTML,CSS,Javascript and in some cases some data that represents a certain part of the UI. A good analogy would be lego pieces where each piece can be considered as a component and we assemble all the pieces in a certain way to build a certain thing. React works the same way. We take all these components and put them together in a systematic way and voila we have our application. Let’s understand this visually-

In the above screenshot of an app I have drawn boxes over certain sections of it. Here each box represents a component. The pink box is the “App” component. This is the root component as all the other components live under it. Next we have the blue box which is the “AddItem” component. As we can see this AddItem component comprises of two form fields and a button. They have some styles applied to them as well. Next we have the yellow box which is the “ListItem” component and this one seems to render a table with two rows and some data. Finally we have the green box which is the “TotalAmount” component and this one seems to be rendering some heading text. As we can infer the total of the two amounts of each of the individual items. With this I hope you have a basic understanding of what are components. They are nothing but a bunch of HTML,CSS, Javascript and sometimes some sort of data.

This idea of dividing your application into individual components is huge. It allows us to reuse these components in various sections of the application. Now that we know a bit about components in React it would be great if we could write one ourselves. Well let’s get to it.

During the initial days of React one of it’s major pain was to set up a development environment but now we have great tools like create-react-app and a ton of sample boilerplate projects available on github that we can make use of to quickly spin up a development environment. We can also leverage the use of websites like CodeSandbox. In this blog I will use create-react-app as that’s how I start writing my React apps but feel to explore around. If you prefer CodeSandbox’s integrated live web editor then feel free to use that instead. So before getting started make sure that you have Nodejs installed on your system. To check if you have Nodejs or not type the following in the terminal-

If it returns a version number like above then you are good to go if not then head over to Node Download. Download the version based on your operating system. Once you have node let’s install create-react-app so head over to a directory where you will store this application and type the following in the terminal-

Don’t forget the -g flag. It means globally install create-react-app in your system. Once that command finishes it’s thing type the following-

This will take sometime so wait for it to finish. Once the command finishes you will have a directory called “sample_app”. Just change to this directory.  Now before starting the server I would like to do a bit of cleanup. So head over to the “src” directory. You will see the list of following files inside it-

I want you to delete certain files as we will not need them. The files are App.css,  App.test.js,  logo.svg,  registerServiceWorker.js. Once that is done head back to the root of the folder that is sample_app and open it up in your favorite text editor. If you need a good one I would suggest Visual Studio Code.

Once you open the folder in a text-editor I want you to open the index.js file and make some changes to it. The changes are as follows-

I will explain what all this code means but first let’s just get the server running. Next open up App.js and make the following changes-

Once all that is done go back to the terminal and type-

This will start a development server. Open up a browser and head over to http://localhost:3000. If it prints the following then everything is good to go-

If not then please go back and make those changes that I have mentioned.Once you have “Hello, React” printing on the screen we are ready to start writing our application. Before that let’s understand some of the code that is already given to us so head over to index.js-

Line 1 is using the ES6 import syntax to import react into our application. The next line is importing the react-dom package. Now you may be wondering what is “react-dom”. Well the simple answer is that React is a library that is not only used in web browsers but in other places as well like mobile for example. If we want to use React for the web we need a way to inject our react app into the browser’s dom and to do that we make use of “react-dom”. Line 3 is importing some styles from the file index.css. Line 4 is importing the App component which is our root level component. All the other components will be put inside the App component so all we have to do is show the app component and all the other components will show up as well. Finally line 6 is where everything happens. To understand line 6 I want you to go over to the public folder of the app and open up “index.html”

We see that there is a div tag with an id of root here on line 28. This is the div where we will attach our React application. So now if we look at  line 6 of code-

render is a method provided to us from the “react-dom” package. This method takes two arguments. The first argument is the component that we want to render i.e. show to the user. In this case it is the App component. Why? because it is our root level component. Next argument is where do we want to put this component. Well we specify here that put it inside the div tag which has an id of root. Next let’s take a look at what’s inside App.js

Line 1 imports react. What’s different here is the { Component } part. This is called “Object destructuring”. It’s a shorthand syntax for extracting out certain properties from an object. Check this article to understand “Object destructuring” if you are not sure about it. Next on line 3 we make use of the ES6 class syntax. Using classes we can describe what our component will look like. The syntax structure is class followed by the name of the component then extends component. Next, inside the class we have a render method. One thing to take note is that all components need to have a render method. Finally inside the render method what seems to be happening is that we are returning some HTML. Well this looks like HTML but isn’t exactly HTML because we all know that we can’t write HTML inside a Javascript file. What you see here is an abstraction. It is called JSX(Javascript and XML). To understand what JSX is doing let’s change the code in App.js a bit. Make the following changes-

Save the file and check your browser. You will see that nothing seems to have changed. Hello React!! still prints out.  Here what I have shown you is the usage of the React.createElement API. What this API does is return an object representation of your dom element. In this case it returns an object representation of the div element with classname of “App” and h1 as the children element. The syntax for this API is “React.createElement(name-of-dom-node,{properties},children). The first parameter represents the name of the dom node for example “div”,”p” etc. The next are the properties which could be class names etc. Finally the third parameter is the children. This children could be the content of the dom node or maybe another dom element itself. As you can see keeping tabs with this kind of syntax is quite cumbersome and might lead to bugs that are difficult to point out hence JSX is a handy abstraction over this. What JSX does is it allows us to write the above code in a structure that we are very familiar with which is the <div>….</div> and converts it to corresponding React.createElement calls. Think of JSX as a translator. We don’t want to speak React.createElement we only want to speak simple HTML like syntax so we do that and JSX takes that as input and spits out React.createElement code. Another thing to note is that when inside JSX we use “className” instead of “class” as “class” is a reserved word in Javascript. Change that above code back to using JSX like so-

If you have read this far then great now you know one of the most important concept in React and that is JSX. So now that we have a basic level of understanding of what all this code means let’s start building our sample application. So lets make some components. Under the src folder make three new files and name them- “AddItem.js” , “ListItem.js”, “TotalAmount.js”. Make sure the first letter is always a capital letter when naming components. Now here I will make use of “Semantic UI” for styling the app but we will write some of our own styles as well. So head back to the terminal and type the following-

Now go back to index.js and make the following change-

Make sure that index.css is imported after “semantic-ui-css/semantic.min.css” as we may need to override some styles. Next go to index.css and make the following change-


Next head back to App.js and make the following change-

What we are doing here is that we are using certain components which are pre-styled from semantic-ui-react. In this case we are using the Container and the Header component. Save the file and check your browser-

Great so our app heading is now perfectly centered. Once this is done head over to AddItem.js the file that we created earlier and add some of the following code-

“AddItem.js” presents us the best way to explain another important concept in React called “Stateless Functional Components”. In React there are two types of component. A component that handles data logic but is not concerned with the look and presentation is called a “Container Component” and a component that is mainly concerned with presenting some sort of an UI to the user but doesn’t know anything about any data is called a “Presentation Component”. In React data can be represented in two ways. One is called Props and the other is called State. We will talk about each of them in later sections. As the name suggest “Stateless Functional Components” are presentation components as they don’t have any state. All they do is show some UI to the user. In this case the AddItem component is showing a form to the user. It doesn’t need to handle any data so it is a stateless functional component. Save the file. Now to use this component head back to App.js and add the following-

Here we import AddItem component in line 3 and use it in line 11. To use a component all we do is put the name of the component in between “< />”. Make sure to use “/” otherwise there will be errors. Save the file and head back to the browser-

I will show you how to add custom styles later on so that we can adjust the width of the form fields and center the entire form. One interesting thing to note that in React components can be represented as simple functions that returns some sort of JSX.

Now as I mentioned earlier data in React can represented either as “props” or as “state”. Let’s understand what are props. In React a parent component can send data to it’s children. We call this one-way data-flow. The data moves from the parent component to the children components. Now why do we need to do this well the children component may need the data to render something on the screen or maybe need to process the data in a different way. One way to pass data around is by using props. Just to give an example let’s head back to App.js and make the following change-

This is just to demonstrate what are props. We will remove it. So if we check line 11 where we use the component. You can see that I have passed an attribute to it as well named “someData” with a value of 42. In React whenever we need to perform some operation or pass in numerical values or boolean values we surround it with a pair of {}. This attribute in AddItem is what we call a prop. We can say that the App component here is passing a prop called someData to AddItem component. Whenever you see a component being used along with some attributes remember that the enclosing component will be the one that is sending that prop to that component. Now how do we get access to this prop. Well it’s pretty simple let’s head back to AddItem.js and make the following change-

The stateless functional component here takes in a parameter called props. This props object contains all the properties this component can have including the one send by it’s parent. To access a specific prop all we do is props.prop_name. Here the name of the prop is someData as discussed above so if we do {props.someData} it will return us the value that we had passed earlier that is 42. So if we check the browser –

We see that 42 has been printed as a header tag. So effectively we have passed some data from our parent component that is App to our children component that is AddItem. Now this data is a read-only data we can’t modify this data. This is one of the distinctions between a prop and a state. Whereas state can be modified a prop is always read only. Now undo these changes but just keep the parameter props in the stateless functional component. Remove everything else.

Next let’s talk about state. Go back to App.js and write the following-

There is a lot going on here so let’s break it down. First we have defined the state as an object which currently has a property called “counter” which has been set with a value of 0. Next we can see that there is a button with an onClick handler attached to it. This onClick is an event which will trigger a function to be executed when somebody clicks on the button. The function here is handleIncrement. This function then makes use of a special method called setState which updates the state of the application. Finally we are able to access the state using this.state.counter.  Question might arise which is where did setState come from well it’s available because “this” refers to the component itself. When we created the App component it came with certain methods that we can make use of and setState is one of them. Always remember to use setState whenever you are trying to update your state. Never mutate your state. By mutate I mean don’t change the value of state directly. Make use of setState. Once the setState method has finished executing it will trigger a re-render which means the render function will execute again but this time with the updated value of the state.  Now if we look at setState we can see that it takes an object as an argument. Inside this object we have access to our state properties so we make use of our only state property which is counter and set its value to whatever this.state.counter + 1 will be.

To summarize use setState whenever you need to update the state and use this.state.property_name whenever you need to access state values and finally React will re-render everytime you call setState. To visualize this take a look at the following diagram-

With that out of the way lets make use of the concept of states and props to build the sample application. Remove all the previous code that we added in App.js. Your App.js file should like the following:

Now write the following code inside App.js

Here we have declared the state object inside the App component. The state object contains three properties. The items array is used for storing the list of items. The item and the amount properties will be used for capturing the value of these respective fields from the form. Now since our form lives inside the AddItem component we pass these state properties to it using props. This has been show in line 16 of the above code. You can see that we have declared two props item and amount whose value is equivalent to whatever the state value will be. As a reminder we can access the state inside a component using this.state.property_name and we can access props using this.props.prop_name.

With that out of the way lets go back to AddItem component and make the following changes:

Now with that change if you go and try to type something up in the form field you will see nothing is getting shown because we have set the value attribute of our inputs to be equivalent to the values of the item and the amount property in App.js state object. To fix this issue we need to use a handler method. The handler method we will use is a handleChange. So write the following in AddItem.js

Here we have used the onChange event handler and hooked it up with a function handleChange which we haven’t created yet so lets do that head back to App.js and write the following code:

The handleChange method takes the event object as its parameter and then uses that event object to find the name of the input that has been changed. The code inside the setState may seem weird but its actually pretty simple. The event object has a property called target which can be used to find which input was changed. So when the user types something in the item name input we can grab the value of whatever the user types by using and we can even get the name of which input was changed by using Here the name property in the inputs resembles the exact same names as was used in the App’s state object. The bracket notation simply means its a computed property which is an ES6 syntax. So whenever Javascript engine looks at line 12 it knows that the “[]” means whats the value for the name property for the input that was typed. It grabs that value and returns it. When the engine looks at the right hand side of the property assignment at “” it retrieves the value of that input typed and places it there. So for example if the user types the name of some item say “Apple” then the left hand assignment of that object will be item and the right hand will yield Apple. Hope this clears the code at line 12. Now we pass this method to our AddItem component as a prop. Remember we can access methods of a component by using this. So to access a method we use this.method_name.  Now with this change if we go back to the browser and type something in the input we see that our problem was fixed. Remember the number input only accepts numbers.

With that out of the way you now have a basic understanding of how to use forms in React.  So with this we know quite a lot of stuff in React. We know how to use components pass props around different components and how to even use states and forms. In the next post we will extend this application and make it working. Thanks a lot for reading this post.