0% found this document useful (0 votes)
423 views195 pages

Mern

The MERN stack is a JavaScript stack used for building full-stack web applications. It comprises MongoDB, Express, React, and Node.js. MongoDB is a document-oriented database that is fast, scalable, and uses JavaScript. Express is a web application framework for Node.js that provides a robust set of features for web and mobile applications. React is a JavaScript library for building user interfaces. Node.js is an open-source runtime environment that allows JavaScript to be run on the server-side. The MERN stack is designed to make the development process smoother and easier.

Uploaded by

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

Mern

The MERN stack is a JavaScript stack used for building full-stack web applications. It comprises MongoDB, Express, React, and Node.js. MongoDB is a document-oriented database that is fast, scalable, and uses JavaScript. Express is a web application framework for Node.js that provides a robust set of features for web and mobile applications. React is a JavaScript library for building user interfaces. Node.js is an open-source runtime environment that allows JavaScript to be run on the server-side. The MERN stack is designed to make the development process smoother and easier.

Uploaded by

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

Mern stack

MERN Stack is a Javascript Stack that is used for easier and


faster deployment of full-stack web applications. MERN Stack
comprises of 4 technologies namely:
MongoDB,
Express,
React and Node.js.
It is designed to make the development process smoother
and easier.
MongoDB: Cross-platform Document-
Oriented Database
• Fast – Being a document-oriented database, easy to index documents. Therefore a faster response.
• Scalability – Large data can be handled by dividing it into several machines.
• Use of JavaScript – MongoDB uses JavaScript which is the biggest advantage.
• Schema Less – Any type of data in a separate document.
• Data stored in the form of JSON –
– Objects, Object Members, Arrays, Values, and Strings
– JSON syntax is very easy to use.
– JSON has a wide range of browser compatibility.
– Sharing Data: Data of any size and type(video, audio) can be shared easily.
• Simple Environment Setup – Its really simple to set up MongoDB.
• Flexible Document Model – MongoDB supports document-model(tables, schemas, columns & SQL) which
is faster and easier.
• Creating a table: If the collection/table doesn’t exist then a new collection/table will be created:
• db.createCollection("collection_name");
Inserting records into the collection:
db.collection_name.insert
(
{
"id" : 1,
"Name" : "Klaus",
"Department": "Technical",
"Organization": “PVPSIT“
}
);
EXPRESS JS
ADVANTAGES AND DISADVANTAGES
COMPANIES USING EXPRESS JS
SAMPLE EXPRESS JS CODE
const express = require('express'),
http = require('http');

const hostname = 'localhost';


const port = 8080;
const app = express();

app.use((req, res) => {


console.log(req.headers);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is a test server</h1></body></html>');

});
const sample_server = http.createServer(app);

sample_server.listen(port, hostname, () => {


console.log(`Server running at http://${hostname}:${port}/`);
});
WHAT IS REACT JS
NODE.JS
NODE JS COMPONENTS
COMPANIES USING NODE JS
Features of ES6
Let Vs Var
The var variables belong to the global scope when you define
them outside a function
var counter;
function increase() {
var counter = 10;
}
// cannot access the counter variable here
for (var i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}

console.log("Outside the loop:", i);


Output?
for (let i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}

console.log("Outside the loop:", i);


output>?
For..of
• ES6 introduced a new loop construct called for...of to
eliminate the standard loop’s complexity and avoid the
errors caused by keeping track of loop indexes.
• – iterate over an array to access each element in the
sequence.
• On top of this, the for...of loop has the ability to create a
loop over any iterable object, not just an array.
Default parameters
function say(message) {
console.log(message);
}
say(); // undefined

function fn(param1=default1, param2=default2,..) {


}
Example
function say(message='Hi') {
console.log(message);
}

say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello'); // 'Hello'
Passing undefined arguments
function createDiv(height = '100px', width = '100px', border = 'solid 1px red') {
let div = document.createElement('div');
div.style.height = height;
div.style.width = width;
div.style.border = border;
document.body.appendChild(div);
return div;
}
createDiv(); //function uses the default values for the parameters.
createDiv(undefined,undefined,'solid 5px blue'); //createDiv(undefined,undefined,'solid 5px blue');
Evaluating default parameters
JavaScript engine evaluates the default arguments at the time
you call the function
function put(toy, toyBox = []) {
toyBox.push(toy);
return toyBox;
}

console.log(put('Toy Car'));
// -> ['Toy Car']
console.log(put('Teddy Bear'));
// -> ['Teddy Bear'], not ['Toy Car','Teddy Bear']
Using other parameters in default values

function add(x = 1, y = x, z = x + y) {
return x + y + z;
}

console.log(add()); // 4
rest
ES6 provides a new kind of parameter so-called rest parameter that has a prefix of
three dots (...). A rest parameter allows you to represent an indefinite number of
arguments as an array

function fn(a,b,...args) {
//...
}
• The last parameter (args) is prefixed with the three-dots ( ...). It’s called a rest
parameter ( ...args).
fn(1, 2, 3, "A", "B", "C"); args array stores [3,'A','B','C']
• fn(1,2); args array []
Set
ES6 provides a new type named Set that stores a collection of
unique values of any type. To create a new empty Set
let setObject = new Set();
The Set constructor also accepts an optional iterable object.
If you pass an iterable object to the Set constructor, all the
elements of the iterable object will be added to the new set:

let setObject = new Set(iterableObject);


let chars = new Set(['a', 'a', 'b', 'c', 'c']);
console.log(chars);
output
Set { 'a', 'b', 'c' }
Add elements to a set
chars.add('d');
console.log(chars);
Set { 'a', 'b', 'c', 'd' }
chars.add('e')
.add('f');
Checking values in a set
let exist = chars.has('a');
console.log(exist);// true
Remove elements
chars.delete('f');
console.log(chars); // Set {"a", "b", "c", "d", "e"}
chars.clear();
console.log(chars); // Set{}
Looping the elements in a set
let roles = new Set();
roles.add('admin')
.add('editor')
.add('subscriber');
for (let role of roles) {
console.log(role);
}
Map
• By definition, a Map object holds key-value pairs. Keys are unique in
a Map’s collection. In other words, a key in a Map object only
appears once.
• Keys and values of a Map can be any values.
When iterating a Map object, each iteration returns a 2-member
array of [key, value].
The iteration order follows the insertion order which corresponds
to the order in which each key-value pair was first inserted into the Map
by the set() method.
Creating a new Map
let map = new Map([iterable]);
let john = { name: 'John Doe' },
lily = { name: 'Lily Bush' },
peter = { name: 'Peter Drucker' };

let userRoles = new Map([


[john, 'admin'],
[lily, 'editor'],
[peter, 'subscriber'],
]);

for (const user of userRoles.keys()) {


console.log(user.name);
}
Spread operator
ES6 provides a new operator called spread operator that consists of three dots (...).
The spread operator allows you to spread out elements of an iterable object such
as an array, map, or set.
const odd = [1,3,5];
const combined = [2,4,6, ...odd];
console.log(combined);
[ 2, 4, 6, 1, 3, 5 ]
this example, the three dots ( ...) located in front of the odd array is the spread
operator. The spread operator (...) unpacks the elements of the odd array.
• The spread operator (...) unpacks the elements of an iterable object.
• The rest parameter (...) packs the elements into an array.
The rest parameters must be the last arguments of a function. However, the spread
operator can be anywhere:
const odd = [1,3,5];
const combined = [...odd, 2,4,6];
console.log(combined);

const odd = [1,3,5];


const combined = [2,...odd, 4,6];
console.log(combined);
JavaScript spread operator and array manipulation

let initialChars = ['A', 'B'];


let chars = [...initialChars, 'C', 'D'];
console.log(chars); // ["A", "B", "C", "D"]

let numbers = [1, 2];


let moreNumbers = [3, 4];
let allNumbers = [...numbers, ...moreNumbers];
console.log(allNumbers); // [1, 2, 3, 4]
let scores = [80, 70, 90];
let copiedScores = [...scores];
console.log(copiedScores); // [80, 70, 90]

let chars = ['A', ...'BC', 'D'];


console.log(chars); // ["A", "B", "C", "D"]
Destructuring
function getScores() {
return [70, 80];
}

let [x, y, z] = getScores();

console.log(x); // 70
console.log(y); // 80
console.log(z); // undefined
classes
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Promises
Promises are used to handle asynchronous operations in
JavaScript.
They can handle multiple asynchronous operations easily and
provide better error handling than callbacks and events.
Promise has four states:
fulfilled: Action related to the promise succeeded
rejected: Action related to the promise failed
pending: Promise is still pending i.e. not fulfilled or rejected yet
settled: Promise has fulfilled or rejected
A promise can be created using Promise constructor.
Syntax
• var promise = new Promise(function(resolve, reject){
//do something
});
• Parameters
– Promise constructor takes only one argument which is a callback
function (and that callback function is also referred as anonymous
function too).
– Callback function takes two arguments, resolve and reject
– Perform operations inside the callback function and if everything
went well then call resolve.
– If desired operations do not go well then call reject.
The fulfilled state indicates that the asynchronous operation was
completed successfully:

The rejected state indicates that the asynchronous operation failed.


Creating a promise
const promise = new Promise((resolve, reject) => {
// contain an operation
// ...

// return the state


if (success) {
resolve(value);
} else {
reject(error);
}
});
• The promise constructor accepts a callback function that
typically performs an asynchronous operation. This function
is often referred to as an executor.
• In turn, the executor accepts two callback functions with
the name resolve and reject.
• A promise is an object that encapsulates the result of an asynchronous
operation.
• A promise starts in the pending state and ends in either fulfilled state or rejected
state.
• Use then() method to schedule a callback to be executed when the promise is
fulfilled, and catch() method to schedule a callback to be invoked when the
promise is rejected.
• Place the code that you want to execute in the finally() method whether the
promise is fulfilled or rejected.
• If the asynchronous operation completes successfully, the executor will call
the resolve() function to change the state of the promise from pending to
fulfilled with a value.
• In case of an error, the executor will call the reject() function to change the
state of the promise from pending to rejected with the error reason.
• Once a promise reaches either fulfilled or rejected state, it stays in that state and
can’t go to another state.
• In other words, a promise cannot go from the fulfilled state to the rejected state
and vice versa. Also, it cannot go back from the fulfilled or rejected state to
the pending state.
• Once a new Promise object is created, its state is pending. If a promise
reaches fulfilled or rejected state, it is resolved.
Consuming a Promise: then, catch, finally
1) The then() method
• To get the value of a promise when it’s fulfilled, you call the then() method of
the promise object. The following shows the syntax of the then() method:
promise.then(onFulfilled,onRejected);
• Code language: CSS (css)The then() method accepts two callback
functions: onFulfilled and onRejected.
• The then() method calls the onFulfilled() with a value, if the promise is fulfilled
or the onRejected() with an error if the promise is rejected.
• The catch() method
• If you want to get the error only when the state of the
promise is rejected, you can use the catch() method of
the Promise object:
promise.catch(onRejected);
Example demo
Symbol
• ES6 introduces a new primitive type called Symbol. They are
helpful to implement metaprogramming in JavaScript
programs.
• const mySymbol = Symbol()
• const mySymbol = Symbol(stringDescription)
• A symbol is just a piece of memory in which you can store
some data. Each symbol will point to a different memory
location. Values returned by a Symbol() constructor are
unique and immutable.
<script>
const s1 = Symbol();
const s2 = Symbol();
console.log(typeof s1)
console.log(s1===s2)
const s3 = Symbol("hello");//description
const s4 = Symbol("hello");
console.log(s3)
console.log(s4)
console.log(s3==s4) </script>
output
Symbol
false
Symbol(hello)
Symbol(hello)
false
modules
• A module can contain variables and functions. A module is nothing
more than a chunk of JavaScript code written in a file.
• By default, variables and functions of a module are not available for
use. Variables and functions within a module should be exported so
that they can be accessed from within other files.
• Modules in ES6 work only in strict mode. This means variables or
functions declared in a module will not be accessible globally.
React life cycle
• every React Component has a lifecycle of its own, lifecycle
of a component can be defined as the series of methods
that are invoked in different stages of the component’s
existence.
• A React Component can go through four stages of its life as
follows.
Four phases

Initialization: This is the stage where the component is constructed with the given Props
and default state. This is done in the constructor of a Component Class.

Mounting: Mounting is the stage of rendering the JSX returned by the render method
itself.

Updating: Updating is the stage when the state of a component is updated and the
application is repainted.

Unmounting: As the name suggests Unmounting is the final step of the component
lifecycle where the component is removed from the page.
• Mounting – Birth of your component
• Update – Growth of your component
• Unmount – Death of your component
render()
The render() method is the most used lifecycle method. You
will see it in all React classes. This is because render() is the
only required method within a class component in React.
Example

The render() method returns JSX that is displayed in the UI. A render() can also return a null if
there is nothing to render for that component.
You should not setState() (modify the state) inside
the render() method as it will result in an infinite loop.

This is because the component calls the render() method


when the state changes.

Therefore, if you update the state inside this method, the


component would keep calling the render() method infinitely.
constructor()

• The constructor is where the initial state and the values are
set in a React component. This method is called before the
component is mounted. The purpose of the constructor is
to,
• Initialize the state
• Bind methods to the component
constructor(props) {
super(props); // Initialize state
this.state = {
currentIndex: 0,
}; // Bind methods
this.addToCart = this.addToCart.bind(this);
}
componentDidMount()

• componentDidMount() is called as soon as the component is


mounted and ready. This is a good place to initiate API calls,
if you need to load data from a remote endpoint.
• This method is called after the component is rendered for
the first time. It is only available after the component is
mounted. At this stage, the component has been mounted
and is available to the DOM.
• This method is called only once in the component lifecycle.
• componentDidMount() {
const { fetchProductById } = this.props; // API call via an
action to retrieve data
fetchProductById(productId);
}
static getDerivedStateFromProps()

• This is the first method that will be called when the component gets
an update. The use case of this method is to update the state based
on prop changes when props aren’t sufficient to be directly used.
Let’s look at this example.
• static getDerivedStateFromProps(props, state)
{
return {favoriteColor: props.favoriteColor };

}Here, the favoriteColor state is updated based on the prop change.


shouldComponentUpdate()

• This method is highly useful to improve application performance. The usual


scenario is where the component always re-renders when the component
receives a new state or new props.
However, using this method, we can control whether the component should re-
render or not for a prop change.
• This method always returns a boolean. If it returns yes, the component will re-
render.
• shouldComponentUpdate() method allows us to avoid unnecessary re-renders.
shouldComponentUpdate(nextProps, nextState) {
// Only update if the count has increased than the current
count
return nextState.count > this.state.count;
}
componentDidUpdate()

• This method is always called right after a component render and has updated
the DOM. It receives two values as arguments,
• prevProps — Props of the component before the update
• prevState — State of the component before the update
• componentDidUpdate = (prevProps) => {
const { currentUser } = this.props;
if (prevProps.currentUser !== currentUser) {
this.setAddress();
this.setPaymentOption();
}
}
componentWillUnmount()

• Common cleanup activities performed in this method


include, clearing timers, cancelling api calls, or clearing any
caches in storage.
Introduction to JSX
JSX is a JavaScript Extension Syntax used in React to easily
write HTML and JavaScript together.

const jsx = <h1>This is JSX</h1>


class JSXDemo extends React.Component
{
render()
{
return <h1>This is JSX</h1>;
}
}
ReactDOM.render(<JSXDemo />, document.getElementById('root'));
Above code converted into
class JSXDemo extends React.Component
{
render()
{
return React.createElement("h1", null, "This is JSX");
}
}
React.createElement() syntax

React.createElement(type, [props], [...children])


• type can be an HTML tag like h1, div or it can be a React
component
• props are the attributes you want the element to have
• children contain other HTML tags or can be a component
Object representation of React.createElement
{
type: 'h1',
props:
{
children: 'This is JSX‘
}
}
Is it Correct?
import React from "react";
import ReactDOM from "react-dom";
const App = () =>
{
return (
<p>This is first JSX Element!</p>
<p>This is another JSX Element</p>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Correct way
import React from "react";
import ReactDOM from "react-dom";
const App = () =>
{
return (
<div>
<p>This is first JSX Element!</p>
<p>This is another JSX Element</p>
</div> );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
JAVASCRIPT code inside JSX
const App = () =>
{
const number = 10;
return (
<div>
<p>Number: {number}</p>
</div>
);
};
Props and states
In a real-time application, components must deal with dynamic
data.
This data could be something internal to the component or
may be the data that is passed from another component.
To bind the data to the component, you need two JS objects
i.e., state and props.
The state is an initial value set for a component, which is used for
interactivity.

constructor() {
super();
this.state = { counter: 1 };
}
• In the above code, the state 'counter' is set to 1
and 'counter' would be accessed as this.state.counter.
When an event occurs in the component, we will update the state of the component using
the setState() method inside the event handler method as shown below:

class Timer extends React.Component {


constructor() {
super ()
this.state = {
counter: 0
}
}
handleClick = (e) => {
this.setState({counter:this.state.counter+1})
}
}
render() {
return(<React.Fragment>
<h2> Seconds Elapsed: {this.state.counter} </h2>
<button onClick = {this.handleClick}> Increment Counter </button>
</React.Fragment>)
}
}
• State is a JavaScript object used to manage the data of an
application
• To associate state with components you can use useState
hook
• useState():
• useState hook is used to add or initialize state value within a
functional component. This hook helps to preserve the
state value of a component.
syntax
• const [count, setCount] = useState(0);
• useState() is a function which takes ‘initialState’ as the
initial value for any state variable and returns 2 values.
• In the above code snippet, count is a state variable which is
initialized with value 0 and setCount is the function used to
update the state count
• Whenever state is updated, the component is re-rendered,
and updated value is displayed on the UI. React remembers
the current value of state between re-renders and provides
the most recent value to the function.
​const [name,setName] = useState("Jack")
const [age,setAge] = useState(0)
import { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css"
function App() {
const [counter, setCounter] = useState(0);
return (
<div>
Counter: {counter}<br/>
<button className="btn btn-primary" onClick={() => setCounter(()=>counter+1)}>Increment</button>
</div>
);
}
export default App;
The state can be updated using an event
handler method as shown
import {useState} from 'react';
function App() {
const [name,setName] = useState("Jack")
const handleChange = () => {
setName("Jill")
}
return (
<div>
Your Name is: {name}<br/>
<button onClick={handleChange}>Change</button>
</div>
);
}
export default App;
State should not be modified directly, but it can be
modified with a special method called setState( ).
• this.state.id = “2020”; // wrong
• this.setState(
{ id: "2020"
}
);
state
• State:
– States are mutable
– They are reserved for interactivity. The component's event
handlers may update the state and trigger a UI update
– The state will be set with a default value when component
mounts and will mutate in time based on user events generated
props
• When we want to pass any data from one component to another component, it is passed as a
prop.
• Props allow us to pass data from one component to another component
• Props are immutable - a component cannot change its props however it is responsible for
putting together
• Props can be accessed as this.props

• How to use props?


• Let's now learn how to pass data to a component:
• <App initial = {10} />
• Here, we are passing a property 'initial' with a value '10', to a component App.
• In the component App, this property would be accessed as this.props.initial
Passing data
Accessing data
Create 2 components as mentioned below:
1. Timer - It holds state and handles button click
2. Resultant - It takes result from Timer component and
displays it
props
• Props:
– Props are immutable
– The child component cannot modify the props. However, when
parent component updates the data that is passed as props then
the Child component gets updated props.
– Whenever props are updated the component gets re-rendered
and displays the latest value in the UI.
Child to parent communication
we can also pass data from the child to the parent component.
If the child component wants to send data to the parent
component, it can send it by invoking a function that is passed
as props from the parent component.
Parent component
import React from 'react';
import Child from './Child';
class App extends React.Component {
constructor() {
super()
this.state = {
name: 'John'
}
}
update = (value) => {
let newValue = value;
this.setState({name:newValue})
}
render() {
return ( <React.Fragment>
<h1>{this.state.name}</h1><br/><br/>
<Child nameValue={this.state.name} update={this.update}/>
</React.Fragment>)
}
The Parent component contains the state 'name', which gets updated in the child
component as shown below:

import React from 'react';


class Child extends React.Component {
constructor() {
super()
this.state = {
nameValue:null
}
}
handleChange = () => {
let newValue = 'Jack'
this.setState({nameValue: newValue})
this.props.update(newValue)
}
render() {
return(<React.Fragment>
<button onClick={this.handleChange}>Change</button>
</React.Fragment>)
}
• In the child component on clicking of the change button,
the value of the state 'nameValue' changes to 'Jack' and the
same value is sent to the parent component by calling the
update() method from Child component
as this.props.update(newValue).
• The update() method is a prop passed to the Child
Component.
• The Parent component gets the updated value from the
child and updates its state.
• It is possible to pass data from the child to the parent
component. If the child component wants to send data to
the parent component, it can sent by invoking a function
that is passed as props from the parent component.
Differences between props and states
• Components receive data from outside with props, whereas they can create and manage their
own data with state
• Props are used to pass data, whereas state is for managing data
• Data from props is read-only, and cannot be modified by a component that is receiving it from
outside
• State data can be modified by its own component, but is private (cannot be accessed from
outside)
• Props can only be passed from parent component to child (unidirectional flow)
• Modifying state should happen with the setState ( ) method
Component communication
• Components can receive data from their parent
components via props, which are essentially properties that
are passed down from the parent component.
• Example
pass a method as props with an example.
Data flow in react
In react data flow is one-way from parent component to child
component. The parent component passes data as props to its
child component, and the child component can only read the
data but cannot modify it.
If the child component wants to change the data, it needs to
send a request to the parent component, and the parent
component will decide whether to modify the data and pass
the updated data as props to the child component.
• defaultProps is used to set default values for props in case
they are not passed explicitly by the component. It is
defined as a static property on the component class.
• PropTypes is used to specify the expected type of props for
a component. It is also defined as a static property on the
component class. If the component passes props that do
not match the expected types, a warning will be logged to
the console in development mode.
Example
React forms
• Handling forms is about how you handle the data when it changes value or gets
submitted.
• In HTML, form data is usually handled by the DOM.
• In React, form data is usually handled by the components.
• When the data is handled by the components, all the data is stored in the
component state.
• You can control changes by adding event handlers in the onChange attribute.
• We can use the useState Hook to keep track of each inputs value and provide a
"single source of truth" for the entire application.
• You can make form elements interactive by setting a
callback to the onChange prop. Form components listen to
changes and they are fired when,
• The value of <input> or <textarea> changes
• Checked state of <input> changes
• Selected state of <input> changes
You should maintain a state for every form
field
• const [username,setUsername] = useState('')
• const [password,setPassword] = useState('')
For updating the value in response to user interaction, the
onChange prop can be used as follows:
<input
style={{ width: "40%" }}
type="text"
value={username}
onChange={(event) => setUsername(event.target.value)}
className="form-control"
placeholder="Enter Name"
/>;
On change of the input field, the value can be fetched using
event.target.value and the corresponding state is updated and
the value attribute is assigned to the corresponding state.
You can update the state within an event handler method
instead of doing it inline with onChange as shown below
We can create two different ways of forms in
React:
1. Controlled component
2. Uncontrolled component
Controlled component
• In HTML, form elements such as <input>, <textarea>, and <select> typically
maintains their own state and that gets updated based on user input.
• But in React, we handle it using state and state gets updated using setState()
method. So an input form element whose value is controlled by React in this
way will be called a controlled component.

• Below is an example of a controlled component where it has a value attribute


and a handler function.
Eg. <input type="text" value={this.state.name} onChange={this.handleData}/>
Uncontrolled component
• The traditional HTML input elements are uncontrolled
component, where the form data is handled by DOM itself.
In uncontrolled component, we do not use the value
attributes.
Below is the example for an uncontrolled component:
• <input type="text" />
• Here, input will not have value attribute and event handler, instead
to get the value from the DOM ref is used as follows:
• <input type="text" ref={this.input}/>
Refs are created using React.createRef() and attached to
React elements via the ref attribute.
Refs are commonly assigned to an instance property when a
component is constructed so they can be referenced
throughout the component.
• When a ref is passed to an element in render, a reference to
the node becomes accessible at the current attribute of the
ref.
• const node = this.myRef.current;
• Data validation is the process of checking whether the data
entered by a user is in the correct format or meets certain
criteria before it is accepted.
• Data sanitization is the process of cleaning and removing
unwanted characters/words from data input.
Example
• we have kept a validation on the content that it is posted
only if the length of the post is less than or equal to 20
characters. If the content contains any bad words like hell,
sadist etc., they are sanitized i.e.; characters are changed to
*.
React Routing
As you know, these days all the web applications are single
page applications (SPA) because in multi-page applications:
• Every request will be sent to the server from the client
• The Server responds to the client with new HTML content
• Every time page reload will happen for every request
• This would increase the round trips to the server and cause
delay in response
SPA overcomes the limitations of multi-page application as described
below:
• Rather than loading a new page from the server on every user
interaction (such as clicking on the login button), it loads an entire
web page containing all views from the server when the application
starts
• As a result, after the initial page load, no server communication
is required for further page updates upon user interaction
• So here, we have to navigate from one view to another
without hitting server. For this React JS provides the react-router-
dom library.
• Routing is a process in which a user is directed to different pages based on their
action or request.
• ReactJS Router is mainly used for developing Single Page Web Applications.
React Router is used to define multiple routes in the application.
• When a user types a specific URL into the browser, and if this URL path matches
any 'route' inside the router file, the user will be redirected to that particular
route.
• React Router is a standard library system built on top of the React and used to
create routing in the React application using React Router Package.
• Most of the social media websites like Facebook, Instagram uses React Router
for rendering multiple views.
React contains three different packages for
routing.
• react-router: It provides the core routing components and
functions for the React Router applications.
• react-router-native: It is used for mobile applications.
• react-router-dom: It is used for web applications design.
To use react routing, first, you need to install
react-router-dom modules in your application.
• $ npm install react-router-dom
Components in React Router
• There are two types of router components:
<BrowserRouter>: It is used for handling the dynamic URL.
<HashRouter>: It is used for handling the static request.
if you're using React Router on the web, you wrap your app inside of
the BrowserRouter component.
What is Route?

• It is used to define and render component based on the


specified path. It will accept components and render to
define what should be rendered.
You can render as many Routes as you'd like.
Routes?
• Whenever you have one or more Routes, you'll most likely
want to wrap them in a Routes.
Link:able to navigate between them. This is
the purpose of the Link component.
To tell Link what path to take the user to when clicked, you
pass it a to prop.
Example
Redux

• Redux is an open-source JavaScript library used to manage application state. React uses Redux
for building the user interface.
• It allows React components to read data from a Redux Store, and dispatch Actions to
the Store to update data. Redux helps apps to scale by providing a sensible way to manage state
through a unidirectional data flow model.
• Redux is not a framework. Redux can be used with any other View library but mostly used with
React.
The main concepts of Redux architecture are:
• Store: The place where the entire state of the application is stored
• Actions: JS objects which encapsulate the events triggered within the application.
• Reducers: Pure functions that modify the state of the application according to the actions
triggered.
With Redux, we can make state data independent of the components, and when needed, a component

can access or update through the Redux store.


Action: Action is a plain JavaScript object. Action is a
command to change the state when an event is triggered.
• Reducer: Reducer changes the state of the application
based on the action triggered. Reducer is a function that
accepts action and current state and modifies the current
state by creating a copy of it based on the action.
• To achieve modularity, you can write multiple reducers in
Redux.
Actions are plain JavaScript objects that must have
• a type property to indicate the type of action to be carried
out, and
• a payload object that contains the information that should
be used to change the state.
{
type: "LOGIN",
payload: {
username: "foo",
password: "bar"
}
}
Reducers
• Reducers are pure functions that take the current state of
an application, perform an action, and return a new state.
The reducer handles how the state (application data) will
change in response to an action.
• Though there can be multiple reducers as your application grows, ultimately,
you can pass only one reducer object to the createStore method.
• We can use the combineReducers() method of Redux to combine multiple
reducers into a single reducing function and then pass it to the createStore
method.
• Whenever an action is triggered the action would reach the root reducer
first and then all the reducers get the action from root reducer.
• The root reducer will combine the state from all the reducers and create
a single new state object and will update the store with the new state.​​
Store:
• Store is responsible for managing the entire state of the
application. State management is centralized in Redux.
Action will be dispatched to the store using the dispatch
method of the store.
• A Store can be created as shown below
import {createStore} from 'redux';
function myReducer() {
}
const store = createStore(myReducer)
Store Methods
1. getState(): This method can be used to get the current state
from the store.
2. dispatch(action): React components should use this method
to dispatch an action whenever an event occurs within the
component. This method dispatches an action and then the
reducer takes care of updating the state
3. subscribe(listener): Used for registering the listeners
We don't have any API's to change the data in the store. The only
way to change the state present in the store is by dispatching actions.
The store would handle actions using reducers.
Redux middleware

• Redux allows developers to intercept all actions dispatched from components


before they are passed to the reducer function. This interception is done via
middleware.
• It provides functionality between action and reducer. After an action is triggered
and before its reduced, middleware can take action.
Advantages of middleware
• Middleware allows pre-processing of actions. We can check for correct syntax,
make sure that they conform to your standards or edit them in some way like
wrapping them in a function
• Perfect for debugging an application
• API calls are happening through middleware so if there is a mistake, you can
check middleware first
Redux flow with thunk
Dispatch this action to the reducer
Integrating Redux in React
• The createStore() is used to create a store that holds the state of the application and the
reducer function is passed to it. The Provider component is used to make the Redux store
available to the rest of the application by passing it as a prop to the Provider component.

• The mapStateToProps() takes the current state of the application as an argument and
returns an object that contains the count property of the state.

• The mapDispatchToProps() takes the dispatch function as an argument and returns an


object that contains two functions: increment and decrement. These functions dispatch the
INCREMENT and DECREMENT actions, respectively.
Integrating Redux in React
App.js file defines the counter component and connects it to the store using the
connect function.
Node.js
React Vs Node
• React is a JavaScript library used for building user interfaces. It is
typically used in the front-end of web applications and allows
developers to create reusable UI components that can be composed
to build complex user interfaces.
• React is used to build interactive web applications with a highly
responsive and dynamic user interface.
• React doesn't provide server-side capabilities, it's used on the client-
side for rendering HTML.
• Node is a server-side JavaScript runtime environment. It
allows developers to build scalable and high-performance
web applications.
• Node is used for server-side scripting and can handle HTTP
requests, manage databases, and perform other server-side
tasks.
• Node is used to build the back-end of web applications and
provides an event-driven, non-blocking I/O model that
makes it highly efficient for handling large amounts of data
Single-threaded event loop model
processing steps:
• A useful feature of Node.js and JavaScript is the ability to
delay execution of code
• for a period of time. This can be useful for cleanup or
refresh work that you do not
• want to always be running. There are three types of timers
you can implement in
• Node.js: timeout, interval, and immediate.
Delaying Work with Timeouts
• Timeout timers are used to delay work for a specific amount
of time. When that time expires, the callback function is
executed and the timer goes away
• Timeout timers are created using the setTimeout(callback,
delayMilliSeconds, [args]) method built into Node.js.
When you call setTimeout(), the callback function is executed after
delayMilliSecondsexpires. For example, the following executes
myFunc() after 1 second:
• setTimeout(myFunc, 1000);
• The setTimeout() function returns a timer object ID. You can
pass this ID to clearTimeout(timeoutId) at any time before
the delayMilliSeconds expires to cancel the timeout
function. For example:
myTimeout = setTimeout(myFunc, 100000);
… clearTimeout(myTimeout);
simple_timer.js: Implementing a series of timeouts at various
intervals

• The console.time() method starts a timer you can use to


track how long an operation takes. You give each timer a
unique name, and may have up to 10,000 timers running on
a given page.
• When you call console.timeEnd() with the same name, the
browser will output the time, in milliseconds, that elapsed
since the timer was started.
Performing Periodic Work with Intervals
• Interval timers are used to perform work on a regular
delayed interval. When the delay time expires, the callback
function is executed and is then rescheduled for the delay
interval again.
• Interval timers are created using the setInterval(callback,delayMilliSeconds,
[args]) method built into Node.js.
• When you call setInterval(), the callback function is executed every interval after
delayMilliSeconds has expired. For example, the following executes
myFunc() every second:
setInterval(myFunc, 1000);
Performing Immediate Work with an
Immediate Timer
• Immediate timers are used to perform work on a function
as soon as the I/O event callbacks are executed, but before
any timeout or interval events are executed. This allows you
to schedule work to be done after the current events in the
event queue are completed.
• Immediate timers are created using the
setImmediate(callback,[args])method built into Node.js.
When you call setImmediate(), the callback function is
placed on the event queue and popped off once for each
iteration through the eventqueue loop after I/O events have
a chance to be called
Using nextTick to Schedule Work
• A useful method of scheduling work on the event queue is the
process.nextTick(callback) function. This function schedules work to be run on
the next cycle of the event loop. Unlike the setImmediate() method,nextTick()
executes before the I/O events are fired.
• This can result in starvation of the I/O events, so Node.js limits the number of
nextTick() events that can be executed each cycle through the event queue by
the value of process.maxTickDepth, which defaults to 1000.
Adding Custom Events to Your JavaScript
Objects
• Events are emitted using an EventEmitter object. This object is included in the
events module. The emit(eventName, [args]) function triggers the eventName
event and includes any arguments provided. The following code snippet shows
how to implement a simple event emitter:
var events = require('events');
var emitter = new events.EventEmitter();
emitter.emit("simpleEvent");
Adding Event Listeners to Objects
• addListener(eventName, callback): Attaches the callback
function to the object’s listeners. Every time the eventName
event is triggered, the callback function is placed in the event
queue to be executed.
• .on(eventName, callback): Same as .addListener().
• .once(eventName, callback): Only the first time the
eventName event is triggered, the callback function is
placed in the event queue to be executed.
• Node.js also provides a package manager called NPM (Node Package Manager) which is a collection of all
open-source JavaScript libraries available in this world. It is the world’s largest software registry
maintained by the Node.js team. It helps in installing any library or module into your machine.

• It is also possible to import an external module into a Node application, using NPM (Node Package
Manager).

• NPM provides a command-line interface "npm" to work with the NPM repository, which comes bundled
with Node. This tool can be used to install, update, or uninstall any package through NPM.

• Installing NPM package: In cmd type as below


• npm install <package_name>[@<version>]
There are two modes of installation through
NPM
• Global
• Local
Global installation
• If we want to globally install any package or tool add -g to
the command. On installing any package globally, that
package gets added to the PATH so that we can run it from
any location on the computer.
• npm install -g <package_name>
eg. npm install -g express
Local installation
• If we do not add -g to your command for installation, the
modules get installed locally, within a node_modules folder
under the root directory. This is the default mode, as well.
• Eg. npm install express
What is package.json file?

• A Node project needs a configuration file named


"package.json". It is a file that contains basic information
about the project like the package name, version as well as
more information like dependencies which specifies the
additional packages required for the project.
• To create a package.json file, open the Node command
prompt and type the below command.
• npm init
examples
Express js
Install express js
• npm install -g express
• npm install express --save
You should install some other important modules along with
express. Following is the list:
• body-parser: This is a node.js middleware for handling JSON, Raw, Text and URL encoded form
data.
• cookie-parser: It is used to parse Cookie header and populate req.cookies with an object keyed
by the cookie names.
• multer: This is a node.js middleware for handling multipart/form-data.
• npm install body-parser --save
• npm install cookie-parser --save
• npm install multer --save
Express.js Request Object

• Express.js Request and Response objects are the


parameters of the callback function which is used in Express
applications.
• The express.js request object represents the HTTP request
and has properties for the request query string, parameters,
body, HTTP headers, and so on.
• app.get('/', function (req, res) {
// --
})
The Response object (res) specifies the HTTP response which is
sent by an Express app when it gets an HTTP request.
What it does
• It sends response back to the client browser.
Express.js GET Request

• GET requests are used to send only limited amount of data


because data is sent into header while POST requests are
used to send large amount of data because data is sent in
the body.
Express.js Routing
• Routing is made from the word route. It is used to
determine the specific behavior of an application. It
specifies how an application responds to a client request to
a particular route, URI or path and a specific HTTP request
method (GET, POST, etc.). It can handle different types of
HTTP requests.
Express.js Cookies Management
Import cookie-parser into your app.

• var express = require('express');


• var cookieParser = require('cookie-parser');
• var app = express();
• app.use(cookieParser());
Applying Route Parameters Using Query
Strings
• Using a defined parameter allows you to define your
parameters by name
• within the route path. You define parameters in the path of
the route using :<param_name>.
• When using defined parameters, req.param is a function
where calling req.param(param_name) returns the value
of the parameter.
• The following code implements a basic :userid parameter
expecting a URL with a /user/<user_id> format:
app.get('/user/:userid', function (req, res) {
res.send("Get User: " + req.param("userid"));
});
For example, consider the following URL:
/user/4983
The res.send() method returns
Get User: 4983
Example demo
• The find() method returns the value of the first element
that passes a test.
• The find() method executes a function for each array
element.
• array.find(function(currentValue, index, arr),thisValue)
Template engine
• A template engine is a software component that allows you
to generate dynamic HTML pages by combining static
template files with data.
• Template engines provide a way to separate the
presentation of data from its content, making it easier to
maintain and modify your application's user interface.
Template engine
• EJS (Embedded JavaScript) is one such template engine for
JavaScript that allows you to embed JavaScript code
directly into your HTML templates.
• It provides a simple and efficient way to generate dynamic
web pages by allowing you to add logic and iterate over
data within your templates.
EJS
• EJS uses a syntax similar to HTML, but with special tags that
allow you to embed JavaScript code. For example, to
output the value of a variable in your template, you would
use the <%= %> tags.
Pug
• Pug is a template engine for Node.js and for the browser
that provides a clean, concise syntax for creating HTML
templates. Pug was previously known as "Jade," but was
renamed in 2016 due to a trademark dispute.
• Pug uses indentation and whitespace to define the
structure of an HTML document, rather than opening and
closing tags.
• This makes Pug templates more concise and easier to read,
especially for complex documents with nested elements.
Demo

You might also like