InP Sem5 final soln
InP Sem5 final soln
● Hooks
Hooks are the new feature introduced in the React 16.8 version. It allows you to
use state and other React features without writing a class. Hooks are the functions
which "hook into" React state and lifecycle features from function components. It
does not work inside classes.
Hooks are backward-compatible, which means it does not contain any breaking
changes. Also, it does not replace your knowledge of React concepts.
When to use a Hooks
If you write a function component, and then you want to add some state to it,
previously you do this by converting it to a class. But, now you can do it by using a
Hook inside the existing function component.
Rules of Hooks
Hooks are similar to JavaScript functions, but you need to follow these two rules
when using them.
1. react-router: It provides the core routing components and functions for the
React Router applications.
2. react-router-native: It is used for mobile applications.
3. 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 --save
● States in React
The state is an updatable structure that is used to contain data or information
about the component. The state in a component can change over time. The
change in state over time can happen as a response to user action or system
event. A component with the state is known as stateful components. It is the
heart of the react component which determines the behaviour of the component
and how it will render. They are also responsible for making a component
dynamic and interactive.
It can be set by using the setState() method and calling setState() method
triggers UI updates. It can only be accessed or modified inside the component or
by the component directly. To set an initial state before any interaction occurs,
we need to use the getInitialState() method.
Example 2:
● Function component-
ReactJS Functional components are some of the more common components that will come across while
working in React. These are simply JavaScript functions. We can create a functional component in React by
writing a JavaScript function. These functions may or may not receive data as parameters. In the functional
Components, the return value is the JSX code to render to the DOM tree.
// Example of Calling
the function with
2. Call the function by using the functional component method.
function name followed
by Parentheses
// Example of Calling
import React from
the function using 1. Comparison between xml ad json.
'react';
component call
import ReactDOM from XML stands for Extensible Markup Language. Provide information
import React from
'react-dom/client'; about a document. Tags are added to the document to provide the
'react';
function Parentheses() extra information. XML is designed to carry data, not to display
import ReactDOM from
{ data. XML is not a replacement for HTML. XML documents are used
'react-dom/client';
return (<h1> to transfer data from one place to another often over the Internet.
function Comp() {
We can call XML properties:
return (<h1> As
function using name of ● Markup language.
usual we can call the
the ● Used for storing and transporting the data.
function using
function
component call</h1>); ● Focuses on data.
followed by
} ● Platform and programming language independent.
Parentheses
const root = ● No predefined tags.
</h1>);
ReactDOM.createRoot(
}
document.getElementB JSON stands for JavaScript Object Notation. It is lightweight data-
const root =
yId('root')); interchange format and easy to read and write than XML. JSON is
ReactDOM.createRoot(
root.render(<Comp />); language independent which supports array, object, string, number
document.getElementB
yId('root')); and values. ×JSON is a syntax for storing and exchanging data. It is
root.render(Parenthese based on a subset of the JavaScript Programming Language. A JSON
s()); filetype is .json. It is originated from JavaScript. In JSON, a map data
structure is used, whereas XML follows a tree structure.
2. Compare between html and xml.
const functionNam Pending - It is the initial state of each Promise. It represents that
the result has not been computed yet.
e = (arg1, arg2, ?..) Fulfilled - It means that the operation has completed.
=> { Rejected - It represents a failure that occurs during computation.
//body of the fu Once a Promise is fulfilled or rejected, it will be immutable.
The Promise() constructor takes two arguments that
nction
are rejected function and a resolve function.
} Syntax: const promise = new Promise((resolve,reject) => {....});
There are three parts to an
Arrow Function or Lambda
Function:
▪ Parameters: A
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
onsubmit Event Type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type. Here we are calling a validate() function before submitting a form data to
the webserver. If validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Each phase contains some lifecycle methods that are specific to the particular phase.
Let us discuss each of these phases one by one.
1. Initial Phase
It is the birth phase of the lifecycle of a ReactJS component. Here, the component
starts its journey on a way to the DOM. In this phase, a component contains the
default Props and initial State. These default properties are done in the constructor of
a component. The initial phase only occurs once and consists of the following
methods.
o getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the creation of
the component or any props from the parent is passed into it.
o getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of
the component.
2. Mounting Phase
In this phase, the instance of a component is created and inserted into the DOM. It
consists of the following methods.
o componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In the
case, when you call setState() inside this method, the component will not re-render.
o componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM.
Now, you can do any DOM querying operations.
o render()
This method is defined in each and every component. It is responsible for returning a
single root HTML node element. If you don't want to render anything, you can return
a null or false value.
3. Updating Phase
It is the next phase of the lifecycle of a react component. Here, we get new Props and
change State. This phase also allows to handle user interaction and provide
communication with the components hierarchy. The main aim of this phase is to
ensure that the component is displaying the latest version of itself. Unlike the Birth or
Death phase, this phase repeats again and again. This phase consists of the following
methods.
o componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the state in
response to prop changes, you should compare this.props and nextProps to perform
state transition by using this.setState() method.
o shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows
you to control the component's behavior of updating itself. If this method returns true,
the component will update. Otherwise, the component will skip the updating.
o componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't change the
component state by invoking this.setState() method. It will not be called,
if shouldComponentUpdate() returns false.
o render()
It is invoked to examine this.props and this.state and return one of the following
types: React elements, Arrays and fragments, Booleans or null, String and Number. If
shouldComponentUpdate() returns false, the code inside render() will be invoked again
to ensure that the component displays itself properly.
o componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method, you can
put any code inside this which you want to execute once the updating occurs. This
method is not invoked for the initial render.
4. Unmounting Phase
It is the final phase of the react component lifecycle. It is called when a component
instance is destroyed and unmounted from the DOM. This phase contains only one
method and is given below.
o componentWillUnmount()
This method is invoked immediately before a component is destroyed and unmounted
permanently. It performs any necessary cleanup related task such as invalidating
timers, event listener, canceling network requests, or cleaning up DOM elements. If a
component instance is unmounted, you cannot mount it again.
No Method Description
Node.js streams are a type of data-handling method and are used to read or write input into output
sequentially. Streams are used to handle reading/writing files or exchanging information efficiently.
Streams are collections of data — just like arrays or strings. The difference is that streams might not
be available all at once, and they don’t have to fit in memory. This makes streams really powerful
when working with large amounts of data, or data that’s coming from an external source
one chunk at a time.
There are four types of streams −
● Readable − Stream which is used for read operation.
● Writable − Stream which is used for write operation.
● Duplex − Stream which can be used for both read and write operation.
● Transform − A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different instance of
times. For example, some of the commonly used events are −
● data − This event is fired when there is data is available to read.
● end − This event is fired when there is no more data to read.
● error − This event is fired when there is any error receiving or writing data.
● finish − This event is fired when all the data has been flushed to underlying system.
// Including stream
module
const stream =
require('stream');
// Creating a
stream and
creating
// a write function
const writable =
new
stream.Writable({
// Write function
with its
// parameters
write:
function(chunk,
encoding, next) {
//
Converting the
chunk of
// data to
string
console.log(chunk.
toString());
next();
}
});
5. Install nodemon
npm install -g nodemon
app.get('/’,
function(req, res){
res.send("Hi!");
});
app.listen(3000);
Run the code=> nodemon index.js
20. Explain routing in expressJS with example.
Routing refers to determining how an application responds to a client request to a particular
endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each
route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
● app is an instance of express.
● METHOD is an HTTP request method, in lowercase.
● PATH is a path on the server.
● HANDLER is the function executed when the route is matched.
res.send('Hello World!')
})
Respond to POST request on the root route (/), the application’s home page:
app.post('/', (req, res) => {
})
})
})
Although working of the browser is not as simple as it seems, since a plenty of internal tasks are performed
before a webpage appears on the screen. The whole process takes place in these three steps:
1. Contact to DNS Server – When a user enters a URL into the address bar and hits ‘enter’, at first
browser contacts the DNS server. A DNS server stores the IP addresses of the server associated with the
corresponding domain names. The DNS server takes the domain name from the browser and returns the
corresponding IP address to the browser.
2. Contact to Server – After getting the IP address of the server for the requested webpage,
browser sends a request to that server for the desired files. For example consider the following
URL:
http://www.engineersgarage.com/articles
This URL is divided into three parts. First one is HTTP – it is a protocol named Hyper Text Transfer
Protocol which defines the way browser communicates with the server. The second part is
www.engineersgarage.com which is translated by the DNS server with the IP address. It is the address of a
computer (Web Server) where the requested web page is stored. The third part is ‘articles’ which tells the
address of the file that is located in the root folder of the website.
HTTP protocols are used to transfer the webpage named ‘articles’ to the browser. The protocol decides the
format as well as the methods of communication between web client and server.
Role of Rendering Engine
Once a user requests a particular document, the rendering engine starts fetching the
content of the requested document. This is done via the networking layer. The
rendering engine starts receiving the content of that specific document in chunks of 8
KBs from the networking layer. After this, the basic flow of the rendering engine
begins.
1. The requested HTML page is parsed in chunks, including the external CSS files
and in style elements, by the rendering engine. The HTML elements are then
converted into DOM nodes to form a “content tree” or “DOM tree.”
2. Simultaneously, the browser also creates a render tree. This tree includes both
the styling information as well as the visual instructions that define the order in which
the elements will be displayed. The render tree ensures that the content is displayed
in the desired order.
3. Further, the render tree goes through the layout process. When a render tree
is created, the position or size values are not assigned. The entire process of
calculating values for evaluating the desired position is called a layout process. In this
process, every node is assigned the exact coordinates. This ensures that every node
appears at an accurate position on the screen.
4. The final step is to paint the screen, wherein the render tree is traversed, and
the renderer’s paint() method is invoked, which paints each node on the screen using
the UI backend layer.