React Tutorial A Step-by-Step Guide(3) — Components in Detail and Sample Project

In this tutorial, I am going to explain the Components of React Application and create a simple React Shopping cart Application.

Now you know how to create a new React Application.

When you create an application using the command you don't have to do any configurations. All the configuration is done for you. However, if you want to customize these configurations for the production environment you can eject that using the command

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single-build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc.) into your project as dependencies in package.json. Technically, the distinction between dependencies and development dependencies is pretty arbitrary for front-end apps that produce static bundles.

In addition, it used to cause problems with some hosting platforms that didn’t install development dependencies (and thus weren’t able to build the project on the server or test it right before deployment). You are free to rearrange your dependencies in package.json as you see fit.

All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point, you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However, we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

Folder Structure

In the folder structure, you will have a folder called “public”. We can add our public assets in our application to this. In that folder, there is a file called index.html and it is a simple HTML file. In the body section, you can see a single div with an id= “root”. This is where the react application going to appear. This div is a container for our React application.

  • App.js— In the src folder, there are basic components and there is a file called App.js. That file is responsible for rendering React Applications.

In the App.js file, there is a built-in class called App. As a react developer you need to understand what classes are and how to use them. In that class, there is a render method where we return a markup. This is something you probably haven't seen before because we can't have a markup like this in JavaScript. This is what we called JSX which is JavaScript XML. This section describes what we are going to show in the UI. To make this code work we have to pass this code through babel which is a modern JavaScript compiler. Babel will take this JSX syntax and convert it into plain JavaScript code that browsers can understand.

We can type modern JavaScript code and babel will convert that code into code that the browser can understand. Use this to check the process behind the conversion.

JSX code converts to React code

In the above image writing JSX code like on the left-hand side is much easier than writing React code on the right-hand side.

index.js — This is the entry point for the application

How to write React code from scratch.

Delete all the files in the src folder and let's write code from the beginning. First, create a file called index.js.

Then we have to import React object from react Module.

import React from 'react';

Import ReactDOM object from react-dom/client.

import ReactDOM from 'react-dom/client';

Now let's define an element and assign a JSX expression. “const” is a new feature in modern JavaScript previously we used only “var”.

const element = <h1>Hello World</h1>

As shown in the previous babel image JSX code converts to React code(React.createElement).

Let's log this element in the console.


Whenever you save this, the application will automatically restart it. This is what we called Hot Module Reloading.

Now go to developer tools and open up the console tab. Then you can see the output of our code.

Console output

This is the output of our JSX expression(React element). You can see the type of the element property is set to ‘h1’ and other properties. Virtual DOM is the lightweight in-memory representation of the UI. But it's not the real browser DOM. This output is part of the Virtual DOM. Whenever the state of this React element is changed React will get a new React element then React will compare this element with the previous one and figure out what is the change. Then it will reload the real DOM and update accordingly.

Now we need to render this element(part of the virtual DOM) inside the real DOM. That's why we need to import ReactDOM on the top of our code.

We can call ReactDOM.render method. As the first argument, we pass the element we want to render. We can pass element objects. As the second argument, we need to specify where in the real DOM need to render this. So we need to get a reference to the Root DOM element using Plain JavaScript. We can use document.getElementById(‘root’). Now your react element will render inside the root.

const element = <h1>Hello World</h1>ReactDOM.render(element, document.getElementById('root'));

Run the code and see the changes.

Here click the developer options and see the id= ”root” element inside the div we have and the react element h1 with the “Hello World”. This is a simple application. But in real-world applications instead of rendering simple elements in the DOM, we render App Component. This App Component is the root component of the Application. It includes children like Navigation Bar, SideBar, Profile, and so on.

React Components in Detail

In this section, I am going to implement a simple shopping cart using React in a detailed manner. Here are the main features of our application.

  • Show Products
  • Show the number of Products on Shopping Cart for each and every selected item.
  • Change the Quantity(Increment and Decrement buttons)
  • Quantity becomes zero decrement button should be disabled.
  • Remove items on the list using the Delete button.
  • Reset button to reset all the quantities to zero.
  • Show the total number of items in the Shopping Cart.

You will learn how to render content dynamically and how to apply CSS classes dynamically.

Steps to create the Application.

Step 1

Create a new React Application.

Step 2

Install Bootstrap into our project. Enter this command in the terminal to install.

npm i bootstrap@5.1.3

Then in the index.js add the import statement for Bootstrap.

import ‘bootstrap/dist/css/bootstrap.css’;

Step 3

Create the first React component. Add a new folder called “components” to the src folder. Then add a new file called “counter.jsx” to the components folder. I highly recommend using the JSX extension instead of using JS because you will get better code completion using this.

In the counter.jsx we need to import react and component class for the React module. I named my component class Counter.

import React, { Component } from 'react';class Counter extends Component {render() {return <h1>Hello Kasun</h1>;}}export default Counter;

In the index.js file import your counter class.

import Counter from './components/counter/Counter';

Now render the Counter component in index.js.

ReactDOM.render(<Counter />, document.getElementById('root'));

Now you can show the content of the Counter component in the UI.

Embedding Expressions

Now let's add a button to our counter. But when you add a button you can see a compilation error called JSX expressions must have one parent element. JSX expressions get compiled by React.createElement(). The first argument of this method is the type of the element. But we have 2 types of elements in our return statement. For that, we need to wrap this in a div tag.

Now go to the developer tools in the browser and see the change.

The first div with the id=”root” is coming from the index.html and it is the container for the React application. Then you can find the second div which we used to wrap out h1 and button elements. This div is doing nothing but only wrapping out elements. For that, we can remove this div and use React.Fragment here.

import React, { Component } from 'react';class Counter extends Component {render() {return (<React.Fragment><h1>Hello Kasun</h1><button>Increment</button></React.Fragment>);}}export default Counter;

Now you only see the root div only.

Adding states for buttons and Increment the quantity

Instead of hard-coding “Hello World” I need to increment a value dynamically. In the Counter, the class adds a property called state and set it to an Object. The state is a special property in React Component and it is on an object that includes any data that the component needs.

Add a property called counter in this object and set it to zero

state = {count : 0}

Now change the h1 element to span and hello world to counter. To do that we can add JavaScript expressions. Use this keyword to refer to the current object. Expression is something that produces value. You can add any expressions.

Ex: 2 + 2, counter + 1, function that returns a value, this.state.count

Now I am going to implement a method for this JavaScript expression. If the value of the state is zero that returns “Zero”, otherwise it returns the value of the counter variable. Here is the code. You can implement any function inside this class component like this.

checkCount(){const { count } = this.state.count;return count === 0 ? 'Zero' : count;}

then inside the span element, you can call this function.

<span> {this.checkCount()} </span>

Now check the browser you will get the output of this implemented code. If you add count as 1 you will get an output like this.

If you add count ad 0 you will get an output like this.

That's all about the components and the expressions. I hope you get a better understanding of how to implement React Applications and how to handle expressions and states. We will continue implementing our remaining Shopping Cart application in the next article. See you in the next article.

Thank You!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kasun Dissanayake

Senior Software Engineer at IFS R & D International || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile