01 - Introduction To React
01 - Introduction To React
What is React ?
Let’s start our first session with React and we will start from scratch, starting from:
What is React ?
[Link] was released by a software engineer working for Facebook – Jordane Walke in 2011. React is a Javascript Library focused on creatin
declarative user interfaces (UIs) using a component-based concept. It’s used for handling the view layer and can be used for web and mobile app
React’s main goal is to be extensive, fast, declarative, flexible, and simple.
React is not a framework, it is specifically a library. The explanation for this is that React only deals with rendering UIs and reserves many things at th
discretion of individual projects. The standard set of tools for creating an application using ReactJS is frequently called the stack.
React is a library for helping developers build user interfaces (UIs) as a tree of small pieces called components. A component is a mixture of HTML an
JavaScript that captures all of the logic required to display a small section of a larger UI. Each of these components can be built up into successive
complex parts of an app.
Now after getting the overview of React, let’s see why react is more popular or choosen over other frameworks:
Speedless. React allows developers to use individual parts of their application on both the client and server sides, and any changes they
make will not affect the application’s logic. This makes the development process extremely fast.
Components support. The use of HTML tags and JS codes makes it easy to work with a huge dataset containing DOM. React acts as
an intermediary that represents the DOM and helps you decide which component requires changes to get accurate results.
Easy to use and learn. ReactJS is incredibly user-friendly and makes any UI interactive. It also allows you to quickly and efficiently build
applications, which is time-saving for clients and developers alike.
SEO Friendly. A common problem complained by most web developers is that traditional Javascript Frameworks often have problems
with SEO. ReactJS solves this problem by helping developers navigate different search engines easily through the fact that the ReactJS
application can run on the server, and the virtual DOM renders and returns it to the browser as a web page**.**
One-way Data Binding. One-way data-binding implies that absolutely anyone can trace all the changes that have been made to a
segment of the data. This is also one of the reasons that makes React so easy.
Just to the gist of the popularity of the React, following are the companies that uses React:
Atlassian
Discord
Uber Eats
Netflix
Airbnb
Snapchat
Trello
Now, before going deep with React, let’s first learn about Single page and Multiple page applications:
Before you start turning your idea into the real application, you have to answer a bunch of important questions. To decide what app model is better fo
you, you should follow content-first approach, which emphasizes the importance of putting your application content before everything else. That
because content is the main reason for which users will or won’t use the application. And this leads us to the most important questions: what content d
you want to present and what content your users will care about the most.
SPA requests the markup and data independently and renders pages straight in the browser. We can do this thanks to the advanced JavaScri
frameworks like React JS, AngularJS, [Link], [Link], [Link] .Single-page sites help keep the user in one, comfortable web space whe
content is presented to the user in a simple, easy and workable fashion.
Pros of a Single Page Application :
SPA is fast, as most resources (HTML+CSS+Scripts) are only loaded once throughout the lifespan of application. Only data is transmitted
back and forth.
The development is simplified and streamlined. There is no need to write code to render pages on the server. It is much easier to get
started because you can usually kick off development from a file [Link] without using any server at all.
SPAs are easy to debug with Chrome, as you can monitor network operations, investigate page elements and data associated with it.
It’s easier to make a mobile application because the developer can reuse the same backend code for web application and native mobile
application.
SPA can cache any local storage effectively. An application sends only one request, store all data, then it can use this data and works
even offline.
There are ofcourse some cons in SPA and some pros in MPA, but as we can determine from above explanation that SPA is anyone’s first choice, and th
is where React come really handy as it solves or removes out most of complexity in buliding SPA’s which we would see as we go along with React.
Now, let’s learn one of the concept which makes the React that much popular i.e., the concept of Virtual DOM:
In order to understand the virtual DOM, let’s first see the What is Real DOM ?
Real DOM
First things first, DOM stands for “Document Object Model”. The DOM in simple words represents the UI of your application. Everytime there is a chang
in the state of your application UI, the DOM gets updated to represent that change. Now the catch is frequently manipulating the DOM affec
performance, making it slow.
Virtual DOM
That’s where the concept of virtual DOM comes in and performs significantly better than the real DOM. The virtual DOM is only a virtual representation
the DOM. Everytime the state of our application changes, the virtual DOM gets updated instead of the real DOM.
Well, you may ask ” Isn’t the virtual DOM doing the same thing as the real DOM, this sounds like double work? How can this be faster
than just updating the real DOM?”
The answer is virtual DOM is much faster and efficient, here is why.
Now that you have a fair understanding of what a Virtual DOM is, and how it can help with performance of your app, lets look into how React leverage
the virtual DOM.
In React every UI piece is a component, and each component has a state. React follows the observable pattern and listens for state changes. When th
state of a component changes, React updates the virtual DOM tree. Once the virtual DOM has been updated, React then compares the current versio
of the virtual DOM with the previous version of the virtual DOM. This process is called “diffing”.
Once React knows which virtual DOM objects have changed, then React updates only those objects, in the real DOM. This makes the performance fa
better when compared to manipulating the real DOM directly. This makes React standout as a high performance JavaScript library.
In simple words, you tell React what state you want the UI to be in, and it makes sure that the DOM matches that state. The great benefit
here is that as a developer, you would not need to know how the attribute manipulation, event handling or the manual DOM updates
happen behind the scenes.
All of these details are abstracted away from React developers. All you need to do is update the states of your component as and when needed an
React takes care of the rest. This ensures a superior developer experience when using React.
Architecture:
In a Model View Controller(MVC) architecture, React is the 'View' responsible for how the app looks and feels.
MVC is an architectural pattern that splits the application layer into Model, View, and Controller. The model relates to all data-related logic; the view
used for the UI logic of the application, and the controller is an interface between the Model and View.
Now let’s see that how can we create our first react project, but before this we need to learn about Node package manager:
Since its a package manager, it is used to manage downloads and handle dependencies of your project.
It is a common saying that
There is a package for everything in npm
So, as we have learned just that npm is installed automatically with [Link], So, let’s first see that how we can install [Link] :
node -v
The system should display the [Link] version installed on your system. You can do the same for NPM:
npm -v
You can get the macOS installer by clicking the Macintosh Installer option - this will download the .pkg installer for [Link]. Make sure you sav
it somewhere that you'll be able to access it!
Now that you've got the installer downloaded, you'll need to run it. The installer is a pretty typical interface - it won't take long to get through it (under
minute), even though there are a few parts to it. You can get through it by following the guide below:
Introduction
Select Continue
License
Select Continue
Select Agree
Installation Type
Select Install
Authenticate with your Mac to allow the Installation
Select Install Software
Summary
Select Close
To verify that [Link] was installed correctly on your Mac, you can run the following command in your terminal:
$ node --version
--version
If [Link] was properly installed, you'll see something close to (but probably not exactly) this:
$ npm --version
--version
As now we are able to install the [Link] and hence npm so, let’s continue our discussion on npm:
npm is written entirely in JavaScript(JS) and was developed by Isaac Schlueter. It was initially used to download and manage dependencies, but it ha
since also used frequently in frontend JavaScript.
npm can manage packages that are local dependencies of a particular project, as well as globally-installed JavaScript tools. In addition to pla
downloads, npm also manages versioning, so you can install any version, higher or lower according to the needs of your project. If no version
mentioned, the latest version of the package is installed.
How to use
→ If [Link] file exists in your project directory, all you need to do is use this command
npm install
This command will initialize the node_modules folder and install all packages that the project needs.
And if you need to update the installed packages, hit
npm update
Note: By default, packages are installed in the local scope. If you need to install the package at global scope, you need to mention the flag -g
This will install the package at the global scope in the system directory.
NPX:
NPX is an NPM package runner that makes it really easy to install any sort of node executable that would have normally been installed using NPM.
There are a number of ways to install node packages, you can have them sitting locally (local to the project) or install globally (in the user environment).
Sometimes, instead of using either of the two install methods above, you may just want to use the package and go.
Sometimes, you might just want to experiment with a list of packages as you may not know exactly what you need.
In these cases, instead of installing locally or globally, you can go straight to running those packages with NPX.
NPX comes bundled with NPM starting with version 5.2+. So, if your version of NPM is 5.2 or higher, then you have NPX installed.
When you run a package using NPX, it searches for the package in the local and global registry, and then it runs the package.
If the package is not already installed, NPX downloads the package files and installs the package, but it will only cache the files instead of saving it.
To use NPX, you would run a command like this:
npx some-package
One great way for you to see how quickly NPX works is to create a react app using:
The above command will generate a react app, named my-app , in the path that the command was run in using the create-react-app packag
NPX then searches for the package in your environment. If it is not found, NPX downloads the files and runs the command to create a new react ap
using just that one line of command.
The
The simplest way to create a React application is by adding it to an existing HTML page via a <script> tag. This method
requires only a few lines of code and no build tools.
You can follow along with a pre-existing website or create an empty HTML file to practice with.
Add an Empty Div to Your HTML Page
The first thing you need to do is open the HTML page you wish to edit and add an empty <div> element.
It looks like this:
id="react-component-container"
<div id= ></div
"react-component-container"> div>>
src="[Link]
<script src=
></script
crossorigin>
crossorigin >
script>
src="[Link]
<script src=
></script
crossorigin>
crossorigin >
script>
src="[Link]"
<script src= ></script
"[Link]"> script>>
>
body>
</body
The top two load React from a CDN. And the third one will load our React component after we create it in the next section.
If you ever move this code into production, make sure you replace "[Link]" with "[Link]" in the two
top script tags.
Create the React Component
In the same folder as the HTML page you've been editing, create a file called [Link] :
$ touch react
[Link]
"use strict"
const e = [Link]
npm init
git init
node_modules
build
Now, let's look at what are the basic dependencies that are needed to run a React app.
Transpiler(Babel)
Transpiler converts ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers. We also use this
transpile JSX by adding presets.
A simple babel config for a React app looks like this. You can add this config in .babelrc file or as a property in [Link].
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
You can add various presets and plugins based on your need.
Bundler(Webpack)
Bundler bundles your code and all its dependencies together in one bundle file(or more if you use code splitting).
npm install webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin --save-dev
--save
[Link] = {
output: {
path: [Link](__dirname, 'build'),
filename: '[Link]',
},
resolve: {
modules: [[Link](__dirname, 'src'), 'node_modules'],
alias: {
react: [Link](__dirname, 'node_modules', 'react'),
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/[Link]',
}),
],
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Boilerplate</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
"scripts": {
"start": "webpack-dev-server --mode=development --open --hot",
"build": "webpack --mode=production"
}
That is it. Now our react app is ready to run. Try the commands npm start and npm run build .
Now let’s see the most popular and easy way to create React app and the one which we will be using everytime:
Upon completion, you will get some quick tips on how to use the application:
Now, after you get the above layout on your screen then open your folder in which you have initialised the react project which in our cas
is myfirstreactapp in Visual Studio Code.
There are different ways to open the folder in your visual studio code:
You can either drag and drop the folder into the visual studio code window.
cd myfirstreactapp
code .
This will also open the folder in your visual studio code.
Now, when the folder is opened in visual studio code, you will see the folder structure as shown below:
So, let’s now learn the project strucutre of our first react app:
myfirstreactapp
├── node_modules
├── public
│ favicon.
├── [Link]
│ ├── index
index.
.html
│ ├── logo192.
[Link]
│ ├── logo512.
[Link]
│ manifest.
├── [Link]
│ robots.
└── [Link]
├── src
│ ├── App.
[Link]
│ App.
├── [Link]
│ App.
├── [Link]
test.
.js
│ ├── index
index.
.css
│ ├── index.
[Link]
│ ├── logo.
[Link]
│ serviceWorker.
├── serviceWorker .js
│ └── setupTests.
[Link]
├── .gititgnore
package.
├── [Link]
lock.
├── [Link]
README.
└── [Link]
create-react-app has taken care of setting up the main structure of the application as well as a couple of developer settings. Most of what you see will n
be visible to the visitor of your web app. React uses a tool called webpack which transforms the directories and files here into static assets. Visitors
your site are served those static assets.
Don’t worry if you don’t understand too much about webpack for now. One of the benefits of using create-react-app to set up our React application is th
we’re able to bypass any sort of manual configuration for webpack.
Now, let’s see every folder and files one by one in detail :
.gitignore
This is the standard file used by the source control tool git to determine which files and directories to ignore when committing code. While this file exist
create-react-app did not create a git repo within this folder. If you take a look at the file, it has taken care of ignoring a number of item
(even .DS_Store for Mac users):
[Link]
This file outlines all the settings for the React app.
dependencies contains all the required Node modules and versions required for the application. In the picture above, you’ll see six
dependencies. The first three, as you may have guessed, are for the purpose of testing. The next two dependencies allow us to
use react and react-dom in our JavaScript. Finally, react-scripts provides a useful set of development scripts for working with
React. In the screenshot above, the react version specified is ^16.13.1 . This means that npm will install the most recent major version
matching 16.x.x. In contrast, you may also see something like ~1.2.3 in [Link], which will only install the most recent minor
version matching 1.2.x.
scripts specifies aliases that you can use to access some of the react-scripts commands in a more efficient manner. For example,
running npm test in your command line will run react-scripts test --env=jsdom behind the scenes.
You will also see two more attributes, eslintConfig and browserslist . Both of these are Node modules having their own set of
values. browserslist provides information about browser compatibility of the app, while eslintConfig takes care of the code linting.
node_modules
This directory contains dependencies and sub-dependencies of packages used by the current React app, as specified by [Link]. If you take
look, you may be surprised by how many there are.
Running ls -1 | wc -l within the node_modules/ directory will yield more than 800 subfolders. This folder is automatically added
the .gitignore for good reason! Don’t worry, even with all these dependencies, the basic app will only be around 50 KB after being minified an
compressed for production.
[Link]
This file contains the exact dependency tree installed in node_modules/. This provides a way for teams working on private apps to ensure that the
have the same version of dependencies and sub-dependencies. It also contains a history of changes to [Link], so you can quickly look back
dependency changes.
public
This directory contains assets that will be served directly without additional processing by webpack. [Link] provides the entry point for the web ap
You will also see a favicon (header icon) and a [Link].
The manifest file configures how your web app will behave if it is added to an Android user’s home screen (Android users can “shortcut” web apps an
load them directly from the Android UI).
src
This contains the JavaScript that will be processed by webpack and is the heart of the React app. Browsing this folder, you see the main App JavaScri
component ([Link]), its associated styles ([Link]), and test suite ([Link]). [Link] and its styles ([Link]) provide an entry into the App an
also kick off the [Link]. This service worker takes care of caching and updating files for the end-user. It allows for offline capabili
and faster page loads after the initial visit.
As your React app grows, it is common to add a components/ directory to organize components and component-related files and a views/ directory
organize React views and view-related files.
As stated, any changes to the source code will live-update here. Let’s see that in action.
Leave the current terminal tab running (it’s busy serving the React app) and open src/[Link] in your favorite text editor. You’ll see what looks like
mashup of JavaScript and HTML. This is JSX, which is how React adds XML syntax to JavaScript. It provides an intuitive way to build React componen
and is compiled to JavaScript at runtime. We’ll delve deeper into this in other content, but for now, let’s make a simple edit and see the update in th
browser.
So, open [Link] and change the main paragraph text to read Hello From AlmaBetter! and save the file as shown below :
To save file after changing you can press:
Now, If you left the terminal running, you should be able to switch over to your browser and see the update as shown below :
Congratulations! You’re now up and running with React. You can now begin adding functionality for your application.
Thank You !