0% found this document useful (0 votes)
104 views77 pages

Sample-eBook - Version 2

This document provides an overview of an HTML and CSS course, a JavaScript course, a ReactJS course, and a Web Development Tooling module. The HTML and CSS course covers topics like creating HTML pages, adding styles with CSS, positioning elements, and semantic HTML5. The JavaScript course covers basics like variables, conditionals, and objects as well as advanced topics like prototypes and ES6 features. The ReactJS course introduces React and covers components, props, states, hooks, and optimization. The Web Development Tooling module discusses Git and GitHub.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views77 pages

Sample-eBook - Version 2

This document provides an overview of an HTML and CSS course, a JavaScript course, a ReactJS course, and a Web Development Tooling module. The HTML and CSS course covers topics like creating HTML pages, adding styles with CSS, positioning elements, and semantic HTML5. The JavaScript course covers basics like variables, conditionals, and objects as well as advanced topics like prototypes and ES6 features. The ReactJS course introduces React and covers components, props, states, hooks, and optimization. The Web Development Tooling module discusses Git and GitHub.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

HTML

HTML
TO
REACT
The Ultimate Guide
NGNINJA
ACADEMY
NgNinja Academy

Table Of Content

HTML and CSS


Module 1 - Getting Started
Create Your First HTML Page
Write the following boilerplate code in index.html file
Run Your First HTML File
Run the application on the Internet for FREE
DOM
When should you use section, div or article?
section
article
div
Headings
Paragraph
Links / Anchor elements
Images
Module 2 - Styling your Webpage
Create a CSS File
Then add your style in your index.html file
Now let's create the body of your Valentine's Day card
Now let's add your first style
Selectors
.class
child .class
#id
element tag
Mix n match
Advanced Selectors
adjacent selector
attributes selector
Backgrounds
Colors
Borders
Fun with Border Radius
Shapes
Shorthand
Circle and leaf
Circle
1 / 10
NgNinja Academy

Leaf
Module 3 - Display and position your elements
Box model
Total width of an element should be calculated like this:
Total height of an element should be calculated like this:
Margins
Margin On Individual Sides
Margin Shorthands
Auto Margin
Paddings
Padding On Individual Sides
Padding Shorthands
Display
Block
Inline
Inline-block
None
Visibility Hidden
Flex
Positions
Static
Relative
Absolute
Fixed
Centering:
Centering Vertically
CSS Float
Clearing Floats
Methods to clear float:
Module 4 - Semantic HTML5
Semantic HTML?
More about Semantic HTML
Difference between HTML and HTML5?
HTML
HTML 5
Below are new semantic elements
What elements have disappeared in the latest HTML?
Difference between <div> and <frame>?
What is HTML5 Web Storage?
localStorage:
sessionStorage:
Module 5 - Flexbox intro and media query
2 / 10
NgNinja Academy

Flexbox
Media queries
Always Design for Mobile First
Orientation: Portrait / Landscape
Let's talk about the sizes - px vs em vs rem
How to calculate PX from REM
More on rem vs em
CSS Grids
Flexbox
Grids
Nested grids
Start-End points of Grid
Module 6 - Quirks, tips, and tricks
FOUC
How to avoid it?
BEM naming convention
OOCSS - Object Oriented CSS
CSS User Agent Styles
Normalizing CSS
Reset CSS
Validate your CSS
Testing Strategies
Conditional CSS

JavaScript
Module 1 - JavaScript Basics
Who created JS?
What is javascript
Why do you love JavaScript?
Your first "hello world" program
Run just JavaScript
Variables
Data Types in JavaScript
Basic Operators
Special Operators
Fun with Operators
JavaScript as Object-Oriented Programming language
Polymorphism Example in JavaScript
3 / 10
NgNinja Academy

Module 2 - Conditionals and Collections


Conditionals
If Else Condition
Ternary Operator
Advanced Ternary
Switch Statements
truthy and falsy values in JavaScript
For Loop
For-In loop
For-Of loop
While loop
Do-While loop
Map Reduce Filter
Map
Reduce
Filter
Module 3 - JavaScript Objects and Functions
JavaScript Object Basics
Access Object Value
JavaScript Functions
Example Function
Invoke Function
Local variables
Function Expressions
Scoping in JavaScript
Two Types
Examples
Example: JavaScript does not have block scope
Constructor Functions
The this keyword
this with example
More this examples
The new Operator
Understand with example
Example of creating an object with and without new operator
Interview Question: What is the difference between the new operator and Object.create
Operator
new Operator in JavaScript
Object.create in JavaScript

Module 4 - Prototypes and Prototypal Inheritance


JavaScript as Prototype-based language
What is a prototype?
4 / 10
NgNinja Academy

Example of Prototype
What is Prototypal Inheritance?
Understand Prototypal Inheritance by an analogy
Why is Prototypal Inheritance better?
Example of Prototypal Inheritance
Linking the prototypes
Prototype Chain
How does prototypal inheritance/prototype chain work in above example?
Module 5 - Advanced JavaScript (Closures, Method Chaining, etc.)
Hoisting in JavaScript
Another example
We get an error with Function Expressions
JavaScript Closures
Closure remembers the environment
IIFE
What is happening here?
Closure And IIFE
JavaScript call() & apply() vs bind()?
bind
Example using bind()
call()
apply

Module 6 - Next Generation JS - ES6 and Beyond


JavaScript Classes
Class methods
Class vs Constructor function
Using Classes - ES6+ Style
let and const and Block scope
let
Example of let
const
Tricky const
Arrow Functions
Another example
Lexical this
Example of lexical this
Destructuring Operator
Example using array
Example using object
Rest Operator
Using Rest Operator
Spread Operator
Example
5 / 10
NgNinja Academy

ReactJS
Module 1 - Getting started
What is react?
Features
Why react / Benefits
Other Benefits
Limitations
What Are SPAs
SPA
Pros
Cons
Installing React
Prerequisites
Install Node
Install Yarn
Install ReactJS using create-react-app
Online Playgrounds
Deploying React App To Internet
Deploy to Netlify
Easy setup deploy
Module 2 - Basics of React
React JSX
JSX - confusing parts
Virtual DOM
Cons of real DOM
Enter -> Virtual DOM
Diffing
React Components
Thinking in components
Component Render
Function Components
Class Components
NOTE: Please prefer using Function components with React hooks whenever you need to
create component that need to track it's internal state.
Pure components
Reusing Components
States And Props
States
6 / 10
NgNinja Academy

Props
Event Handling
Bind this
Passing Arguments
Two Way Binding
One way data binding
Two Way - 2 way binding
Module 3 - Styling your components
Inline Styles
CSS Stylesheets
Dynamic Styles
Module 4 - Advanced React
Conditional Rendering
Outputting Lists
Keys
Higher Order Components
Cons of HOC
Render Props
Con
Component Lifecycle
initialization
mounting
componentWillMount()
componentDidMount()
static getDerivedStateFromProps()
updating
componentWillReceiveProps()
shouldComponentUpdate()
getSnapshotBeforeUpdate()
componentWillUpdate()
componentDidUpdate()
unmount
Error handling
componentDidCatch()

Module 5 - React hooks


React Hooks Basics
Why React Hooks?
useState React Hook
useEffect React Hook
More About useEffect
Cleanup
useRef React Hook
7 / 10
NgNinja Academy

Two Use Cases


Context
React.createContext
Context provider
Consuming context
useContext
Module 6 - App performance optimization
Improve React app performance
Memoization
When to use it?
useMemo
Lazy Loading
Suspense
Suspense - Data Fetching
This approach is called Render-as-You-Fetch
Sequence of action in the above example

Web Development
Module 1 - Web Development Tooling
Git and GitHub Basics
What is Git
Install Git
Create Git project
Adding a file to your repo
Committing your file
Git clone
How to clone Git repo?
Git Branching
Checkout the branch
Merging branches
Git status
Webpack
Installing Webpack
Webpack in-depth
Webpack config
Module 2 - HTTP and API
What is HTTP
8 / 10
NgNinja Academy

HTTP is a stateless protocol


HTTP Headers
SSL and TLS
SSL handshake process
Web Services
How do web services work?
Why web services?
RESTful web services - REST API
Benefits of REST APIs
More details about REST APIs
GraphQL
Simple Example
Benefits of GraphQL / Why GraphQL?
Setup GraphQL
Create First GraphQL Application
Data Access Layer
Data store
Create a schema file schema.graphql
Creating your first resolver
Query
Nested Query
Dynamic Queries
Mutations
Setting up GraphQL client
Online Playgrounds
GraphQL vs RESTful APIs
Apollo
Apollo client
Apollo Server
Module 3 - Web Application Performance
List of ways to reduce page load time?
How to lazy load images?
Method 1
Example
Method 2
Example
Web Worker
How Web Workers work
Terminating the worker thread
Web workers use cases
Important points about Web workers
Web workers cons
Server-side rendering SSR vs Client-side rendering CSR
Client-side rendering
Advantages of Client-Side Rendering
9 / 10
NgNinja Academy

Disadvantages of Client-Side Rendering


Server-side rendering
Advantages of Server-Side Rendering
Disadvantages of Server-Side Rendering
Module 4 - Web security
Authentication vs Authorization
Authentication
Authorization
OAuth
How does OAuth work?
JSON Web Token - JWT
Structure of JWT
Popular analogy to explain JWT
How JWT works
Advantages of JWT
Disadvantages of JWT
Local storage vs Session storage
localStorage
sessionStorage
Web attacks
CSRF
How does CSRF work?
Defense against CSRF
XSS
How XSS work?
Defense against XSS
CORS
CORS Example
Principles of secure coding
Secure your Web application
Disable cache for web pages with sensitive data
Use HTTPS instead of HTTP
Prevent Content-Type Sniffing
Security in JavaScript

Roadmap To Advanced Web Developer - Beginner


Roadmap To Advanced Web Developer - Advanced
Interesting Project Ideas

10 / 10
NgNinja Academy

HTML and CSS

1 / 66
NgNinja Academy

Module 1 - Getting Started

Create Your First HTML Page


Create an app folder on your computer
Create file named index.html inside app folder on your computer
Open that page in your favorite text editor
I personally use VSCode

Write the following boilerplate code in index.html file


This is your HTML boilerplate code
You are telling the browser that index.html is an HTML file and render it as an HTML website
head tag is where you declare meta-data, title, and link your style files
body tag is where you actually start writing your web page codes
The visible part of the HTML document is between <body> and </body>
title tag is used to define your page title
h1 tag is used to render a heading on your page

<!DOCTYPE html>
2 / 66
NgNinja Academy

<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<h1>My First Web Page</h1>
</body>
</html>

Run Your First HTML File


To run your application locally -
Save your changes to the index.html page
Then imply open your index.html file in the browser

Run the application on the Internet for FREE


If you want to run your application on the Internet and share the URL with your partner follow these
steps
Go to Netlify Drop
Drop the folder that contains your HTML and CSS file (if you have one) on that page where it says
Drag and drop your site folder here
And Voila! It should create a unique URL that you can simply share with your partner
You can see the working example here

If I do not put <! DOCTYPE html> will HTML5 work?


No, browser will not be able to identify that itʼs a HTML document and HTML 5 tags will not
function properly.
Modern browsers are clever enough to render the HTML content, but it may not be optimized
correctly.

3 / 66
NgNinja Academy

DOM
Document object model

HTML document is represented as tree


Every tree node is an object
document object represents the DOM tree
<html> node is at the root
<head> and <body> are its children
The leaf nodes contain text of the document
"My Application", "This is title", and "This is link" are the leaf nodes
DOM api is available to capture user events and give access to its children
NOTE: If we put something after </body> end tag, then that is automatically moved inside the
body, at the end, as the HTML spec requires that all content must be inside <body>.

NOTE: Modern browsers are smart. If the browser encounters malformed HTML, it automatically
corrects it when making the DOM. For ex: browser will auto insert <html> tag at the top is not
provided.
4 / 66
NgNinja Academy

5 / 66
NgNinja Academy

Some pages are not included in the sample.

6 / 66
NgNinja Academy

Module 4 - Semantic HTML5

Semantic HTML?
It is a coding style
Semantic elements == elements with a meaning
Good for SEO
Good for accessibility
Especially for visually impaired people
Which rely on browser speech, screen readers to interpret page content clearly

Check out the image above


Every semantic element clearly describes its meaning to both the browser and the developer
Avoid using simple div tags everywhere. It does not clearly express the intention.
Use elements like header, nav, section, article, aside, footer
All these elements are built with specific purpose - they are good for SEO too
More about Semantic HTML
<b></b> for bold, and <i></i> for italic should not be used
7 / 66
NgNinja Academy

They are just formatting


They do not provide indication of meaning and structure
Use <strong></strong> and <em></em>
Provide meaning ---> emphasis for example
Non-semantic elements: <div> and <span> - Tells nothing about its content
Semantic elements: <form>, <table>, and <article> - Clearly defines its content

8 / 66
NgNinja Academy

Some pages are not included in the sample.

9 / 66
NgNinja Academy

Module 5 - Flexbox intro and media query

Media queries
It was introduced in CSS3
It uses @media rule to include CSS only if a certain condition is true

Media queries allow you to target any platform you desire and write specific styles for that platform
This is how you write responsive styles
Different styles for desktops vs tablets vs mobiles
Simple example below

// If the browser window is smaller than 500px, the background color will
change to lightblue:

@media only screen and (max-width: 500px) {


body {
background-color: lightblue;
}
}

Below are the breakpoints for targeting devices of your interest


10 / 66
NgNinja Academy

/* Extra small phones */


@media only screen and (max-width: 600px) {

/* Portrait tablets and large phones */


@media only screen and (min-width: 600px) {

/* Landscape tablets */
@media only screen and (min-width: 768px) {

/* Laptops/desktops */
@media only screen and (min-width: 992px) {

/* Large laptops and desktops */


@media only screen and (min-width: 1200px) {

Always Design for Mobile First


It means style for mobiles first
Then include desktop styles in media queries

/* Default styles for mobile phones */


.mobile-styles {
width: 100%;
}

/* Styles for desktop in media queries */


@media only screen and (min-width: 768px) {

/* Style For desktop: */


.desktop-styles {
width: 100%;
}
}

11 / 66
NgNinja Academy

Orientation: Portrait / Landscape


These are queries which apply depending on the orientation of browser/device

@media only screen and (orientation: landscape) {


body {
background-color: lightblue;
}
}

12 / 66
NgNinja Academy

Some pages are not included in the sample.

13 / 66
NgNinja Academy

JavaScript

14 / 66
NgNinja Academy

Module 1 - JavaScript Basics

Who created JS?


Brendan Eich when working at NetScape
It was created in 10 days
What is javascript
JavaScript is an interpreted language
It means it doesn't need a compiler
It executes instructions directly without compiling
It is platform independence, dynamic typing
The source code is evaluated JUST before executing it
It is open-source and cross-platform compatible
It is created by NetScape
It has object-oriented capabilities
Why do you love JavaScript?
It is easy to start using
JavaScript can be used on any platform
It performs well on every platform
You can build web, IOT, mobile apps using JavaScript
It can be used on the Frontend, Backend, and also in the databases like MongoDB
It is dynamic in nature ex: objects and arrays can be of mixed types

15 / 66
NgNinja Academy

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

Variables
Variables are containers
They store data values
For ex: var x = 5
5 is the value stored in variable x
In programming, just like in mathematics, we use variables to hold values

16 / 66
NgNinja Academy

Look at the illustration above


var is the keyword used to declare a variable
In JavaScript you can also use const or let
If you don't use any keyword - the variable will be declared in a global scope
foo is the name of the variable
Basically you give a name to some value
11 is the value you are storing in variable foo
This value can be anything you'd like
number, string, object, function - anything

// More examples

var x = 10 // number variable


var x = "hi" // string variable

17 / 66
NgNinja Academy

Some pages are not included in the sample.

18 / 66
NgNinja Academy

Module 3 - JavaScript Objects and Functions

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

19 / 66
NgNinja Academy

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'


}

20 / 66
NgNinja Academy

Interview Question: What is the difference between the new operator and
Object.create Operator
new Operator in JavaScript
This is used to create an object from a constructor function
The new keywords also execute the constructor function

function Car() {
console.log(this) // this points to myCar
this.name = "Honda";
}

var myCar = new Car()


console.log(myCar) // Car {name: "Honda", constructor: Object}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // true
console.log(myCar.constructor) // function Car() {}
console.log(myCar.constructor === Car) // true
console.log(typeof myCar) // object

Object.create in JavaScript
You can also use Object.create to create a new object
But, it does not execute the constructor function
Object.create is used to create an object from another object

const Car = {
name: "Honda"
}

var myCar = Object.create(Car)


console.log(myCar) // Object {}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // ERROR
console.log(myCar.constructor) // Anonymous function object
console.log(myCar.constructor === Car) // false
console.log(typeof myCar) // object

21 / 66
NgNinja Academy

Some pages are not included in the sample.

22 / 66
NgNinja Academy

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"
23 / 66
NgNinja Academy

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

Using Classes - ES6+ Style


24 / 66
NgNinja Academy

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

25 / 66
NgNinja Academy

Some pages are not included in the sample.

26 / 66
NgNinja Academy

ReactJS

27 / 66
NgNinja Academy

Module 1 - Getting started

What is react?
It is a UI library developed at Facebook
Create interactive, stateful, and reusable components
Example:
Instagram.com is written in React completely
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

28 / 66
NgNinja Academy

29 / 66
NgNinja Academy

Some pages are not included in the sample.

30 / 66
NgNinja Academy

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
31 / 66
NgNinja Academy

// 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!

32 / 66
NgNinja Academy

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

33 / 66
NgNinja Academy

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

34 / 66
NgNinja Academy

Some pages are not included in the sample.

35 / 66
NgNinja Academy

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

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)

36 / 66
NgNinja Academy

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');

37 / 66
NgNinja Academy

You can initiate your state variable with an object too

const [profile, setProfile] = React.useState({


language: 'react',
job: 'Google'
});

38 / 66
NgNinja Academy

Some pages are not included in the sample.

39 / 66
NgNinja Academy

Web Development

40 / 66
NgNinja Academy

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

Check out the illustration above. Here's a simple flow.


There are two parts
One your local setup on your machine
Two the remote setup where your project files are on the github
You keep coding in your "working folder" on your computer
41 / 66
NgNinja Academy

Once you feel you have come to a point where you need to save changes such that a history is
maintained for it - that's where you start the commit process
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
You will first have to install Git to be able to use it
You can follow the steps from their official docs - https://git-scm.com/
Once you install verify it by running this command

git

// sample output excerpt

usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]

42 / 66
NgNinja Academy

[--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 Ngninja

// Ngninja is your project name. It can be anything you want.

cd Ngninja

When you run this command a Git repository will be created


And you will go inside that directory

43 / 66
NgNinja Academy

Some pages are not included in the sample.

44 / 66
NgNinja Academy

Module 3 - Web Application Performance

List of ways to reduce page load time?


Write and include your CSS on top
Add your JavaScript references at the bottom
Lazy loading use defer in script tag - <script src="index.js" defer></script>
Reduce your image size
Use webp image format
They provide lossless compression
Use svg whenever possible
They are smaller than bitmap images, responsive by nature
They work well with animation
Use browser caching on your API requests
Delivering cached copies of the requested content instead of rendering it repeatedly
Reduces the number of client-server round trips
Use fragment caching
It stores the output of some code block that remains unchanged for a very long time
It is an art of caching smaller elements of non-cacheable dynamic website content
Example: Redis object cache
Reduce load on the Database server
Heavy queries - complicated joins should be put on caching servers. Like Redis.
Your Database should be hit minimum times possible
Reduce simple queries
Add minimum table join queries
Add master-slave Database config
Master is the true copy
Slaves are replicates
Writes happen on master
Reads can happen on slaves
Have multiple masters to reduce downtime during updates
Do Database sharding
Simple formula: ID's mod by N
There are other sophisticated algorithms you can use

How to lazy load images?


There are plugins available too
Below are some methods using vanilla JavaScript
45 / 66
NgNinja Academy

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');
};

});

46 / 66
NgNinja Academy

Some pages are not included in the sample.

47 / 66
NgNinja Academy

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.eyJuYW1lIjoiQm9iYnkgVGFibGVzIiwiaWF0I
joxNTE2MjM5MDIyLCJpc0FkbWluIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJ1c2Vyc01ha2UiOnR
ydWUsInVzZXJzQmFuIjp0cnVlLCJ1c2Vyc0RlbGV0ZSI6ZdEsc2V9fQ.HFRcI4qU2lyvDnXhO-
cSTkhvhrTCyXv6f6wXSJKGblk

Header
48 / 66
NgNinja Academy

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

49 / 66
NgNinja Academy

Popular analogy to explain JWT


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
50 / 66
NgNinja Academy

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

51 / 66
NgNinja Academy

Some pages are not included in the sample.

52 / 66
NgNinja Academy

Roadmap To Become Web Developer - Beginner

53 / 66
NgNinja Academy

12 Week Plan Overview


Things You Will Learn In This 12 Weeks
HTML deep dive
CSS deep dive
JavaScript fundamentals
Web Development fundamentals
Chrome developer tools
Git Basics
Interview Prep

54 / 66
NgNinja Academy

12 Week Plan Details

Week 1
HTML
Anatomy of HTML
history, what can HTML do
What is DOM
What are DOM nodes
Tags - HTML, Body, Head, Nav
Tags - Div, P, Section, Span
CSS
What is Box-model
Selectors - Id, Class, Element-tag
Properties - Color, Background-color, Border
Properties - Margin, Padding
Chrome Developer Tools
Elements tab
select DOM element through dev-tool
Inspect an element
Inspect styles of the element
Change styles through the inspect tool
Delete classes from the element
Add new class to the element through the dev tool
Exercise
. Create HTML page
. Add Navigation bar with items - Home, About, Contact Us
. Set background color of navigation bar to Blue
. Add a text paragraph inside Div element below navigation bar

55 / 66
NgNinja Academy

Some pages are not included in the sample.

56 / 66
NgNinja Academy

Week 6
HTML
Radio buttons
Checkboxes
When to use Radio buttons vs When to use Checkboxes
CSS
Introduction - What and Why Flexbox
Flexbox properties
flex-direction
flex-wrap
just-content
align-items
JavaScript
Builtin Functions
Custom Functions and Methods
Write a custom function
Call that custom function from another function
Scoping in JavaScript
Function scope vs Block scope
What is hoisting
Git
Install Git locally
Use git -v command on command line
Merging remote branch X into your local branch Y
Deleting a local branch
Exercise
. Dynamically update the image source
. Create a dropdown list using flexbox and list elements
. Write a function to alert "Hello World" message
. Write a function that takes in a string and a number as arguments and console logs its value
. Find length of this string - "I love JavaScript"
. Change the case to all-capital for this string - "I love JavaScript"

57 / 66
NgNinja Academy

Some pages are not included in the sample.

58 / 66
NgNinja Academy

Roadmap To Advanced Web Developer - Advanced

59 / 66
NgNinja Academy

12 Week Plan Overview


Things You Will Learn In This 12 Weeks
Advanced HTML and CSS
JavaScript deep dive
ReactJS Fundamentals
TypeScript
Advanced Web Development Concepts
Algorithms and Data Structures Fundamentals
Git power user
Interview Prep

60 / 66
NgNinja Academy

12 Week Plan Details

Week 1
HTML
Refresh the tags
HTML, Body, Head, Nav
Div, P, Section, Span
Anchor, Images
,
Lists Tables
What is DOM
How does DOM work
What is DOM hierarchy
CSS
Box-model
Selectors - Id, Class, Element-tag
Properties - Color, Background-color, Border
Properties - Margin, Padding
Decoupling CSS and HTML
What and Why CDN
JavaScript
Primitive data types - Numbers, Boolean, String, etc
Complex data types - Array, Objects
Variables - var, let, const
What is the difference between them
When to use which type of declaration
Exercises
Write a function that takes in an array of mixed data types and returns the array in reverse
order
Implement a clickable image that will take you to your favorite website

61 / 66
NgNinja Academy

Some pages are not included in the sample.

62 / 66
NgNinja Academy

Week 6
JavaScript
Immutable Data Structures
JavaScript as Functional Programming language
Currying
ReactJS
Installing ReactJS
What is JSX
What is a React component
Why do you need components
Creating your first React App
using create-react-app utility
Git
Cherry-picking a particular commit
Rebasing your branch with the other branch
Creating pull requests
Squashing multiple commits into one single commit
Chrome Developer Tools
Networks tab - All, XHR, JS
Networks tab - Inspect XHR query request
Networks tab - Inspect XHR query response
Exercises
Create a react application
Create a React component that displays details of a TODO task
task name, description, due dates, priority
Demonstrate cherry-picking a particular commit
Commit changes to branch X
Goto branch Y and cherry pick the last commit from branch X and push it to the
branch Y

63 / 66
NgNinja Academy

Some pages are not included in the sample.

64 / 66
NgNinja Academy

Interesting Project Ideas

65 / 66
NgNinja Academy

Interesting Project Ideas


. Build your reusable component library - like bootstrap
Create a style-guide/storyboard
Make them responsive
Build it on top of a latest framework like React
. Weather app using 3rd party API beginner
Getting comfortable with 3rd party APIs is very much encouraged by the interviewers
It shows that you are comfortable with understanding the documentation and debugging an
unknown territory

Some items are not included in the sample.

. Image carousal / slider beginner - Show left/right buttons to change the images - Have a timer to
change the images after X seconds - Pull images from a folder or from CDN - Build it using simple
HTML, CSS, JavaScript (without library/framework)
. Quote of the day beginner - Single page application - Show quote for the day - Change quote
every single day - Pull quote from a JSON file - Twist: or you can show a different quote every time
user refreshes the page - Twist 2: You can build similar app for Joke of the day

66 / 66

You might also like