0% found this document useful (0 votes)
28 views82 pages

Module 5 React

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
28 views82 pages

Module 5 React

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 82

Full Stack Development

Presentation Material
Department of Computer Science & Engineering
Semester
Course Code: 20CS2406 IV
:
Course Title: FSD Year: II
Sec -A-Prof. Gaurav Kumar, B-Dr.Kiran Malagi, C-Prof.Chhaya,D-
Faculty Name: Prof.Gousia,E-Prof.Veena,F-Prof. Debasmita, I-Dr.Sindhu Menon

1
MODULE 4—(refer notes)
React.JS: Introducing React ,Main Principles of React, Building your first
react app, Components in React, Transferring properties, Dealing with
State, The Component life cycle,Virtual DOM, JSX,

2
REACT, FEATURES, ADVANTAGES, COMPONENTS (EXAMPLE,
DIFFERENCES),PROPS, STATE , (THEIR DIFFERENCES,EXAMPLES), LIFECYCLE-
METHODS, EXAMPLES

3
Introduction to React
•React is a JavaScript library created by Facebook.
•React is a tool for building UI components.
•React is an open-source frontend JavaScript library which is used for building
user interfaces especially for single page applications.
•It is used for handling view layers for web and mobile apps.
•ReactJS is a simple, feature rich, component based JavaScript UI library.
•It can be used to develop small applications as well as big, complex
applications
•React versions The initial version, 0.3.0 of React is released on May, 2013 and
the latest version, 17.0.1 is released on October, 2020.

4
*How does React Work?
React creates a virtual DOM in memory, where it does all the necessary
manipulating, before making the changes in the browser DOM.
React only changes what needs to be changed!
React finds out what changes have been made, and React changes only
what needs to be changed.

5
*Features
The salient features of React library are as follows:

• Solid base architecture


• Extensible architecture
• Component based library
• JSX based design architecture
• Declarative UI library

6
Benefits and Applications of React
Benefits
• Easy to learn
• Easy to adapt in modern as well as legacy application
• Faster way to code a functionality
• Availability of large number of ready-made component
• Large and active community

Applications
• Facebook, popular social media application
• Instagram, popular photo sharing application
• Netflix, popular media streaming application
• Code Academy, popular online training application 7
Babel Compiler
Babel is a JavaScript compiler which compiles many variant (es2015, es6, etc.,) of
JavaScript into standard JavaScript code supported by all browsers
Babel is used to compile the JSXcode into JavaScript code.

To install Babel and it’s React companion, run the below command:

8
Main Principles of React
The main principle of React is creating a functional(functional programming),
component-based interface.
It promotes a programmatic approach to UI development with good support for
DRY and many SOLID principles.
It also greatly favors using pure javascript over a DSL.
It is the View of the stack, and is mature, well-supported and has a robust, mature
ecosystem…enough to be able to be a great tool in the toolbelt for even the largest
business application.

9
Architecture of the React Application
React library is just UI library and it does not enforce any particular pattern to write a
complex application.
Developers are free to choose the design pattern of their choice. React community
advocates certain design pattern.

10
Architecture of the React Application
•React app starts with a single root component.
•Root component is build using one or more component.
•Each component can be nested with other component to any
level.
•Composition is one of the core concepts of React library. So, each
component is build by composing smaller components instead of
inheriting one component from another component.
•Most of the components are user interface components.
•React app can include third party component for specific purpose
such as routing, animation, state management, etc

11
*Building your first react app
Setting Up React Project:
1. Install globally create react app hit this command in command line after installing node:
npm install -g create-react-app
2. Go to the directory where you want to create the project and hit:
create-react-app<appname>
3. To run a webserver and serve the new application:
yarn start
4. To minify and bundle the JS code for optimization:
yarn run build
5. Start the test runner. Unit tests can be written using JEST
yarn test
6. Pull out configurations and build dependency files to project directory irreversible step, only if we
want to manage configuration on our own:
yarn run eject

12
Components in React
Components let you split the UI into independent, reusable pieces,
and think about each piece in isolation. Conceptually, components are
like JavaScript functions. They accept arbitrary inputs (called “props”)
and return React elements describing what should appear on the
screen.

13
Rendering a Component

We only encountered React elements that represent DOM


tags
const element = <div />;
Elements can also represent user-defined components:

const element = <Welcome name="Sara" />;

When React sees an element representing a user-defined


component, it passes JSX attributes and children to this
component as a single object.
We call this object “props”.
14
Example, this code renders “Hello, Sara” on the page:
This program in same file( u can write function in
different file also)

function Welcome(props) {
return<h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;


ReactDOM.render(
element,
document.getElementById('root') ); 15
What happens in this example:
1. We call ReactDOM.render() with the
<Welcome name="Sara" /> element.
2. React calls the Welcome component with {name: 'Sara'} as the
props.
3. Our Welcome component returns a <h1>Hello, Sara</h1> element
as the result.
4. React DOM efficiently updates the DOM to match
<h1>Hello, Sara</h1>.

16
Function and Class Components Converting a
Function to a Class

You can convert a function component like Clock to a class in five


steps:
1. Create an, with the same name, that extends React.Component.
2. Add a single empty method to it called render().
3. Move the body of the function into the render() method.
4. Replace props with this.props in the render() body.
5. Delete the remaining empty function declaration

17
The simplest way to define a component is to write a JavaScript function
Functional component

function Welcome(props) {
return<h1>Hello, {props.name}</h1>;

OR

Class Component
class Welcome extends React.Component {
render() {
return<h1>Hello, {this.props.name}</h1>;
}
}

The above two components are equivalent from React’s point of view.

Props are arguments passed into React components. 18


*React Props
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes:

Example

● Add a "brand" attribute to the Car element:


constmyelement = <Car brand="Ford" />;
● The component receives the argument as a props object
Use the brand attribute in the component:
class Car extends React.Component {
render() {
return<h2>I am a {this.props.brand}!</h2>; } }
19
Making the Clock component reusable and encapsulated
This can be achieved by setting up its own timer and update itself every second
1. Update the following changes in index.html
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>

function component with react update the following changes in indexjs


function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}

function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}

setInterval(tick, 1000);

20
Class component with react update the following changes in index.js

class Clock extends React.Component { function tick() {


render() { ReactDOM.render(
return ( <Clock date={new
<div> Date()} />,
<h1>Hello, world!</h1> document.getElementById('
<h2>It is {this.props.date.toLocaleTimeString()}.</h2> root')
</div> );
); }
}
} setInterval(tick, 1000);

21
* * Composing Components (
https://reactjs.org/docs/components-and-props.html)
Components can refer to other components in their output. This lets us use the same component abstraction for any level of
detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
Example, we can create an App component that renders Welcome many times
function Welcome(props) {
return<h1>Hello, {props.name}</h1>; }
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />, document.getElementById('root') 22
Extracting Components
functionUserInfo(props) {
Try it on CodePen
return (
<div className="UserInfo">
following is index.js
<Avatar user={props.user} />
<div className="UserInfo-name">
Function format Date(date) {
{props.user.name}</div>
returndate.toLocaleDateString();
</div> );}
}
function Comment(props) {
function Avatar(props) {
return (
return (
<div className="Comment">
<img
<UserInfo user={props.author} />
className="Avatar"
<div
src={props.user.avatarUrl}
className="Comment-text">{props.text}</div>
alt={props.user.name}
<div className="Comment-date">
/>
{formatDate(props.date)}
);
</div>
}
</div> );} 23
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};

ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);
24
*Component Constructor
• If there is a constructor() function in your component, this function will be
called when the component gets initiated.
• The constructor function is where you initiate the component's properties.
• In React, component properties should be kept in an object called state.
• The constructor function is also where you honor the inheritance of the
parent component by including the super() statement, which executes the
parent component's constructor function, and your component has access to
all the functions of the parent component (React.Component).

25
Create a constructor function in the Car component, and add a color property:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return<h2>I am a Car!</h2>; } }

Use the color property in the render() function:


Example
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() { 26
* Difference between state and props in react
Props:
• Props are read-only.
• Props are immutable so, it cannot be modified.
• Props allow you to pass data from one component to other component as an
argument.
• Props make component reusable.
• Props are external and are controlled by renders.
Example:
function A(props) {
return<h1>{props.message}</h1>
}
render(<A message=”hello” />,document.getElementById(“root”));

27
State:
• State changes can be asynchronous.
• states are mutable so, it can be modified using “this.setState”
• State holds information about the components.
• State cannot make components reusable.
• State is internal and are controlled by React Component.
Example:
class A extends React.Component{
constructor(props) {
super(props)
this.state={data:"Sample Data"}
}
render() {
return(<h2>Class State data: {this.state.data}</h2>)
}
}
render(<A />, document.getElementById("root")); 28
For example, this code renders “Hello, Sara” on the page:

function Welcome(props) {
return<h1>Hello, {props.name}</h1>; }
const element = <Welcome name="Sara" />;
ReactDOM.render( element, document.getElementById('root') );
Try it on CodePen
Let’s recap what happens in this example:
1. We call ReactDOM.render() with the <Welcome name="Sara" />
element.
1. React calls the Welcome component with {name: 'Sara'} as the props.
2. Our Welcome component returns a <h1>Hello, Sara</h1> element as
the result.
3. React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1>.
29
*Function and Class Components
Converting a Function to a Class
You can convert a function component like Clock to a class in five steps:
1. Create an ES6 class, with the same name, that extends React.Component.
2. Add a single empty method to it called render().
3. Move the body of the function into the render() method.
4. Replace props with this.props in the render() body.
5. Delete the remaining empty function declaration.

30
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
Try it on CodePen

31
Consuming and Transferring the Same Prop
If your component wants to consume a property but also wants to pass it along, you can repass it
explicitly with checked={checked}.
This is preferable to passing the full props object since it's easier to refactor and lint.
Function FancyCheckbox(props) {
var { checked, title, ...other } = props;
varfancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
varfancyTitle = checked ? 'X ' + title : 'O ' + title;
return (
<label>
<input {...other}
checked={checked}
className={fancyClass}
type="checkbox"
/>
{fancyTitle} 32
Rest and Spread Properties ...
Rest properties allow you to extract the remaining properties from an object into a new object.
It excludes every other property listed in the destructuring pattern.

This is an experimental implementation of an ECMAScript proposal.


var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }

33
Transferring with Underscore
If you don't use JSX, you can use a library to achieve the same pattern. Underscore supports
_.omit to filter out properties and _.extend to copy properties onto a new object.

functionFancyCheckbox(props) {
var checked = props.checked;
var other = _.omit(props, 'checked');
varfancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
return (
React.DOM.div(_.extend({}, other, { className: fancyClass })) ); }

34
Dealing with State and props
Props in React
Props are inputs to components. They are single values or objects containing a set of values
that are passed to components on creation using a naming convention similar to HTML-tag
attributes.
The primary purpose of props in React is to provide following component functionality:
i. Pass custom data to your component.
ii. Trigger state changes.
iii. Use via this.props.reactProp inside component's render() method.
Example, let us create an element with reactProp property:
<Element reactProp={'1'} />
This reactProp name then becomes a property attached to React's native props object which
originally already exists on all components created using React library.
props.reactProp 35
Combining State and Props
The following example shows how to combine state and props in your app. We are setting the state in our parent
component and passing it down the component tree using props.
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from props...",
content: "Content from props...” } }
render() {
return (
<div>
<Header headerProp = {this.state.header}/>
<Content contentProp = {this.state.content}/>
36
</div> ); } }
class Header extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
</div> ); } }
class Content extends React.Component {
render() {
return (
<div>
<h2>{this.props.contentProp}</h2>
</div> ); } }

37
export default App;
main.js
import React from 'react';
importReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));
Only thing that is different is the source of our data, which is now
originally coming from the state.
When we want to update it, we just need to update the state, and all
child components will be updated.

38
import React from 'react';
Changing the state Object
importReactDOM from 'react-dom';
<h1>My {this.state.brand}</h1>
class Car extends React.Component { <p>
constructor(props) { It is a {this.state.color}
super(props); {this.state.model}
this.state = { from {this.state.year}.
brand: "Ford", </p>
model: "Mustang", <button
color: "red", type="button"
year: 1964 onClick={this.changeColor}
}; >Change color</button>
} </div>
changeColor = () => { );
this.setState({color: "blue"}); }
} }
render() {
return ( ReactDOM.render(<Car />,
<div> document.getElementById('root'));
39
State
State is a JavaScript object that stores component’s dynamic data and it enables a component
to keep track of changes between renders.
Because state is dynamic, it is reserved only for interactivity so you don’t use it for static React
projects.
State can only be used within a class and usually the only place where you can assign this.state
is the constructor.
class Greeting extends React.Component {
constructor() {
super();
this.state = {
name: 'John Smith‘ } }
render() {
return<h1>Hello, my name is { this.state.name }</h1>; } } 40
class Greeting extends React.Component {
state = {
name: 'John Smith‘ } }
render() {
return<h1>Hello, my name is { this.state.name }</h1>; } }

State in React Component is its own local state, which means the state cannot be accessed
and modified outside the component and can only be used inside it, probably that will remind
you of a function own local scope.

41
Why should we not update the state directly
If you try to update state directly then it won't re-render the component.
//Wrong
this.state.message = 'Hello world'

Instead use setState() method. It schedules an update to a component's state object. When
state changes, the component responds by re-rendering.
//Correct
this.setState({ message: 'Hello World' })

42
Adding Local State to a Class
We will move the date from props to state in three steps:

1. Replace this.props.date with this.state.date in the render() method:


class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div> ); } }

43
2. Add a class constructor that assigns the initial this.state:

class Clock extends React.Component {


constructor(props) {
super(props);
this.state = {date: new Date()}; }

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div> ); } }

44
Note how we pass props to the base constructor:
constructor(props) {
super(props);
this.state = {date: new Date()};
}
Class components should always call the base constructor with props.
3. Remove the date prop from the <Clock /> element:
ReactDOM.render(
<Clock />,
document.getElementById('root')
);

45
The result looks like this:

class Clock extends React.Component {


constructor(props) {
super(props);
this.state = {date: new Date()}; }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div> ); } }

ReactDOM.render(
<Clock />,
document.getElementById('root') );
46
Manual Transfer
Most of the time you should explicitly pass the properties down. This ensures that you only
expose a subset of the inner API, one that you know will work
functionFancyCheckbox(props) {
varfancyClass = props.checked ? 'FancyChecked' : 'FancyUnchecked';
return ( <div className={fancyClass} onClick={props.onClick}>
{props.children}
</div> ); }
ReactDOM.render(
<FancyCheckbox checked={true} onClick={console.log.bind(console)}>
Hello world!
</FancyCheckbox>,
document.getElementById('example') );
47
Transferring with ... in JSX
List out all the properties that you would like to consume, followed by ...other.

var { checked, ...other } = props;


This ensures that you pass down all the props EXCEPT the ones you're consuming
yourself.

Function FancyCheckbox(props) { var { checked, ...other } = props;


varfancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
// `other` contains { onClick: console.log } but not the checked property
return ( <div {...other} className={fancyClass} /> ); }
ReactDOM.render( <FancyCheckbox checked={true}
onClick={console.log.bind(console)}>
Hello world!
</FancyCheckbox>,
48
Use the destructuring pattern when transferring unknown other
props.

functionFancyCheckbox(props) { varfancyClass = props.checked ?


'FancyChecked' : 'FancyUnchecked';
// ANTI-PATTERN: `checked` would be passed down to the inner
component
return ( <div {...props} className={fancyClass} /> ); }

49
*Lifecycle methods of Components
The three phases are: Mounting, Updating, and Unmounting.
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a
component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()

50
1.constructor
The constructor() method is called before anything else, when the component is
initiated, and it is the natural place to set up the initial state and other initial values.
The constructor() method is called with the props, as arguments, and you should
always start by calling the super(props) before anything else, this will initiate the
parent's constructor method and allows the component to inherit methods from its
parent (React.Component).

3. render
The render() method is required, and is the method that actually outputs the HTML to
the DOM.
componentDidMount
The componentDidMount() method is called after the component is rendered

51
Updating
The next phase in the lifecycle is when a component is updated.
A component is updated whenever there is a change in the component's state or
props.
React has five built-in methods that gets called, in this order, when a component is
updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
The render() method is required and will always be called, the others are optional
and will be called if you define them.

52
Unmounting
The next phase in the life cycle is when a component is removed from the DOM, or
unmounting as React likes to call it.
React has only one built-in method that gets called when a component is
unmounted:
● componentWillUnmount()
componentWillUnmount
The component Will Unmount method is called when the component is about to be
removed from the DOM.

53
*Real DOM
DOM stands for “Document Object Model”
The DOM in simple words represents the UI of your application.
What makes DOM manipulation slow?
The DOM is represented as a tree data structure. Because of that, the changes and updates to
the DOM are fast. But after the change, the updated element and it’s children have to be re-
rendered to update the application UI. The re-rendering or re-painting of the UI is what makes
it slow.

54
*Virtual DOM
The virtual DOM is only a virtual representation of the DOM. Everytime the state of our
application changes, the virtual DOM gets updated instead of the real DOM.
Virtual DOM is much faster and efficient.
How is Virtual DOM faster?
When new elements are added to the UI, a virtual DOM, which is represented as a tree is
created. Each element is a node on this tree. If the state of any of these elements changes, a new
virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual DOM
tree.
Once this is done, the virtual DOM calculates the best possible method to make these changes
to the real DOM. This ensures that there are minimal operations on the real DOM. Hence,
reducing the performance cost of updating the real DOM.

55
Virtual DOM tree and the diffing process
The red circles represent the nodes that have changed. These nodes represent the UI
elements that have had their state changed.

56
*How does React use Virtual DOM
In React every UI piece is a component, and each component has a state. React
follows the observable pattern and listens for state changes. When the state of a
component changes, React updates the virtual DOM tree. Once the virtual DOM
has been updated, React then compares the current version of the virtual DOM
with the previous version of the virtual DOM. This process is called “diffing”.
Once React knows which virtual DOM objects have changed, then React updates
only those objects, in the real DOM. This makes the performance far better when
compared to manipulating the real DOM directly. This makes React standout as a
high performance JavaScript library.
React render() function
render() is where the UI gets updated and rendered. render() is the required
lifecycle method in React.
render() function is the point of entry where the tree of React elements are
created.
57
When a state or prop within the component is updated, the render()
will return a different tree of React elements. If you use setState()
within the component, React immediately detects the state change and
re-renders the component.
React then figures out how to efficiently update the UI to match the
most recent tree changes.

This is when React updates its virtual DOM first and updates only the
object that have changed in the real DOM.

58
Batch Update
React follows a batch update mechanism to update the real DOM. Hence, leading
to increased performance.
This means that updates to the real DOM are sent in batches, instead of sending
updates for every single change in state.
The repainting of the UI is the most expensive part, and React efficiently ensures
that the real DOM receives only batched updates to repaint the UI.

59
Virtual DOM in React

There is a process called “Critical Rendering Path” and the flow of this process
goes like that:

60
1- HTML gets parsed into a tree of nodes (think of nodes as
elements), each node consists of a value and this tree is called
the DOM (Document Object Model).
so the following line of code:

The DOM representation of this single HTML element is


going to look something like that: A node of h1 that holds
inside of it a value

2- CSS also gets parsed into a tree of


nodes called CSSOM (CSS Object
Model) so the following line of code:

61
Will be parsed into this visual representation:
A node of h1 that holds property

62
3. If there is any JavaScript script link in the HTML
filethe browser will send a request to the script link
and download the JS file.
depending on where the JS file was requested in
the HTML file, it will be executed, if you place it
inside the head tag or in the middle or at the end of
the HTML file then it will be executed as soon as it
is received.
Therefore, it is important to place your JS script tag
at the end of the HTML file just in case if the JS file
depends on its execution on an element that might
have not been parsed or rendered yet…Or you can
add the “defer” or “async” attribute to the script tag
to intentionally delay JS execution until the HTML
parsing process is done.

63
4- Now the browser construct
the render tree which is a
combination of the DOM and
CSSOM, and we have this
representation of the render
tree:
WAIT! before we get into how
the render tree looks like, can
you have a look at this piece of
code and guess if it’s going to be
added to the render tree?

64
If you have guessed that span will
NOT be added to the render tree, then
you are right because the render tree
only cares about what is visible.
This means if the div had a property
display: none then both h1 and span
won’t be added to the render tree.
And now the visual representation of
this code should look like this:

65
5- Layout stage where the browser evaluates what is the position of each element and how much width and height it will
take…etc.
6- Paint stage where the browser paints the elements on the page.
Lets understand why React introduced virtual DOM.
Let’s “metaphorically speaking” assume that we have a website like Facebook with millions of data being rendered to the
page, what if a junior developer at Facebook decided to do something very simple such as changing text color. Can you
imagine how extremely heavily this is going to be? Imagine that now the browser has to re-render millions of components
and make thousands of requests and go through the flow of CRP from scratch again to parse HTML, CSS, and download JS
Files and execute it then make judgments on which nodes on both DOM and CSSOM that should be inserted in the render
tree?
Now imagine all of this has to be re-rendered again every time a change happens like someone changes the color of the text.
So what is the benefit of Virtual DOM?
It saves the day!
What React does under the hood is create a copy of the real DOM and store this copy in the memory and this is the “Virtual
DOM” and whenever a change happens a new version of the Virtual DOM is created with the new updates applied to it.
Now we have 2 Virtual DOMS, one is the exact copy of the real DOM and the other one is the new version with the applied
changes.
React does traverse through both trees and figure out the differences between them through a process or an algorithm
called “The diff algorithm” AKA reconciliation.
Now, React kept track of which nodes got changed, and instead of re-rendering the entire real DOM, it will simply re-render
the changed nodes.
The pros are obvious, you get to have faster performance, and re-painting flow won’t be costly on the performance or the
server. 66
JSX
JSX stands for JavaScript XML.
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.
Consider this variable declaration:
const element = <h1>Hello, world!</h1>;
This tag is called JSX, and it is a syntax extension to JavaScript. We recommend using it with
React to describe what the UI should look like.
Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any
createElement() and/or appendChild() methods.
JSX converts HTML tags into react elements.

67
Consider two examples, the first uses JSX and the second does not:
JSX:
constmyelement = <h1>I Love JSX!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
Example 2
Without JSX:constmyelement = React.createElement('h1', {}, 'I do not use JSX!');
ReactDOM.render(myelement, document.getElementById('root'));
In the first example, JSX allows us to write HTML directly within the JavaScript code.
JSX is an extension of the JavaScript language based on ES6, and is translated into regular
JavaScript at runtime.

68
Expressions in JSX
With JSX you can write expressions inside curly braces { }.
The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will
execute the expression and return the result:
Example
Execute the expression 5 + 5:
Const myelement = <h1>React is {5 + 5} times better with JSX</h1>;
Inserting a Large Block of HTML
To write HTML on multiple lines, put the HTML inside parentheses:
Example
Create a list with three list items:constmyelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li> 69
One Top Level Element
The HTML code must be wrapped in ONE top level element.
So if you like to display two headers, you must put them inside a parent element, like a div
element
Example
Wrap two headers inside one DIV element:constmyelement = (
<div>
<h1>I am a Header.</h1>
<h1>I am a Header too.</h1>
</div>
);
JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.

70
Elements Must be Closed
JSX follows XML rules, and therefore HTML elements must be properly closed.
Example
Close empty elements with />
constmyelement = <input type="text" />;
JSX will throw an error if the HTML is not properly closed.

71
More Examples(for Tutorial)
In the example below, we declare a variable called name and then use it inside JSX by wrapping
it in curly braces:
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(element, document.getElementById('root')
);
You can put any valid JavaScript expression inside the curly braces in JSX.
For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.

72
In the example below, we embed the result of calling a JavaScript
function, formatName(user), into an <h1> element.

functionformatName(user) {
returnuser.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

const element = (
<h1>
Hello, {formatName(user)}!
</h1>);
73
JSX is an Expression Tool

After compilation, JSX expressions become regular JavaScript function calls and evaluate to
JavaScript objects.
This means that you can use JSX inside of if statements and for loops, assign it to variables,
accept it as arguments, and return it from functions:
function getGreeting(user)
{
if (user) {
return<h1>Hello, {formatName(user)}!</h1>;
}
return<h1>Hello, Stranger.</h1>;
}

74
Specifying Attributes with JSX
You may use quotes to specify string literals as attributes:
const element = <div tabIndex="0"></div>;
You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <imgsrc={user.avatarUrl}></img>;
Don’t put quotes around curly braces when embedding a JavaScript expression in
an attribute. You should either use quotes (for string values) or curly braces (for
expressions), but not both in the same attribute.

75
Rendering Elements
React Render HTML
React's goal is in many ways to render HTML in a web page.
React renders HTML to the web page by using a function called ReactDOM.render().
The Render Function
The ReactDOM.render() function takes two arguments, HTML code and an HTML
element.
The purpose of the function is to display the specified HTML code inside the specified HTML element.
Example
Display a paragraph inside the "root" element:
ReactDOM.render(<p>Hello</p>, document.getElementById('root'));
The result is displayed in the <div id="root"> element:
<body>
<div id="root"></div> 76
The HTML Code
The HTML code in this tutorial uses JSX which allows you to write HTML tags inside the JavaScript code:
Example
Create a variable that contains HTML code and display it in the root node:
const myelement = (
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Elsa</td>
</tr>
</table>
); 77
The Root Node
The root node is the HTML element where you want to display the result.
It is like a container for content managed by React.
It does NOT have to be a <div> element and it does NOT have to have the id='root':
Example
The root node can be called whatever you like:
<body>
<header id="sandy"></header>
</body>
Display the result in the <header id="sandy"> element:
ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));

78
Rendering an Element into the DOM
Let’s say there is a <div> somewhere in your HTML file:
<div id="root"></div>
We call this a “root” DOM node because everything inside it will be managed by React DOM.
Applications built with just React usually have a single root DOM node. If you are integrating
React into an existing app, you may have as many isolated root DOM nodes as you like.
To render a React element into a root DOM node, pass both to ReactDOM.render():
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try it on CodePen
It displays “Hello, world” on the page.

79
Updating the Rendered Element
React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a
single frame in a movie: it represents the UI at a certain point in time.
With our knowledge so far, the only way to update the UI is to create a new element, and pass it to ReactDOM.render().
Consider this ticking clock example:
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);

Try it on CodePen 80
React Only Updates What’s Necessary
React DOM compares the element and its children to the previous one, and only applies the
DOM updates necessary to bring the DOM to the desired state.
You can verify by inspecting the last example with the browser tools: Even though we create an
element describing the whole UI tree on every tick, only the text node whose contents have
changed gets updated by React DOM.

81
THANK YOU

82

You might also like