React 1 V1
React 1 V1
Introduction
It lets you compose complex UIs from small and isolated pieces of code
called "components".
Introduction
React is a library for building user interfaces and one of its perks is that the
library itself imposes a strict data flow to the developer.
The difference between MVC and Flux is that latest implements unidirectional data flow.
So your data can move only one direction i.e. Action -> Middleware -> Store -> View.
MVC is bidirectional; you can change Model from View and from Controller.
Download VSCode & Node JS
1. Download VSCode
https://code.visualstudio.com/download
2. Download Node JS if not installed at. NPM comes along with Node JS
https://nodejs.org/en/download/
3. https://github.com/facebook/create-react-app
Create React Application Using NPX
We can also create react application using npx(node package execute), a package
runner tool that comes with npm 5.2+.
Create <some-folder>, go to the folder and execute the following either from CLI or
VSCode terminal.
npx create-react-app my-app
cd my-app
npm start
Note: NPM is a package manager, you can install node.js packages using NPM. NPX is a tool to
execute node.js packages.
If any issues while creating the project, clear npm cache using the following command.
F:\Corporate Training\KLS\react-projects>npm cache clean --force
Production Build
When you’re ready to deploy to production, running npm run build will
create an optimized build of your app in the build folder.
Create React application doesn’t handle backend logic or databases; it just creates a
frontend build pipeline, so you can use it with any backend you want.
Under the hood, it uses Babel and webpack, but you don’t need to know anything about
them.
When you’re ready to deploy to production, running npm run build will
create an optimized build of your app in the build folder.
React designs simple views for each state in your application, and React will
efficiently update and render just the right component when your data
changes.
So, to make it faster, React implements a virtual DOM that is basically a DOM
tree representation in Javascript.
So when it needs to read or write to the DOM, it will use the virtual
representation of it. Then the virtual DOM will try to find the most efficient
way to update the browser’s DOM.
How does React Work
Unlike browser DOM elements, React elements are plain objects and are
cheap to create. React DOM takes care of updating the DOM to match the
React elements.
The reason for this is that JavaScript is very fast and it’s worth keeping a DOM
tree in it to speed up its manipulation.
Although React was conceived to be used in the browser, because of its design
it can also be used in the server with Node.js.
How Does React Work
How Does React Work?
React works by taking over an HTML div and injecting JavaScript into it. React
will inject all of the awesome cool JavaScript into this section of our site.
Under the hood, Create React App uses Webpack with html-webpack-plugin.
Our configuration specifies that Webpack uses src/index.js as an “entry point”. So
that’s the first module it reads, and it follows from it to other modules to
compile them into a single bundle.
When webpack compiles the assets, it produces a single (or several if you use
code splitting) bundle(s). It makes their final paths available to all plugins. We are
using one such plugin for injecting scripts into HTML.
You can see a UI broken down into multiple individual pieces called
components and work on them independently and merge them all in a parent
component which will be your final UI.
2. Using a Class
Functional Components
Components in React basically return a piece of JSX code which tells what should
be rendered on the screen.
function Democomponent(){
return <h1>Welcome Message!</h1>;
}
React Components
Class Components: The class components are little more complex than the
functional components.
The functional components are not aware of the other components in your
program whereas the class components can work with each other. We can pass
data from one class component to other class components. We can use
javascript ES6 classes to create class-based components in React.
Note: React Hooks were introduced in 16.8 version as a way to use state and side-
effects ( lifecycle methods in class components) in React functional components.
React hooks let you use state and React lifecycle features without using class and
React component lifecycle methods.
DOM & Virtual DOM
What is DOM?
DOM, abbreviated as Document Object Model, is a World Wide Web Consortium
(WWW) standard logical representation of any webpage.
In easier words, DOM is a tree-like structure that contains all the elements and it’s
properties of a web page as it’s nodes.
Before React, Developers directly manipulated the DOM elements which resulted in
frequent DOM manipulation and each time an update was made the browser had to
recalculate and repaint the whole view according to the particular CSS of the page,
which made the total process to consume a lot of time.
The Virtual DOM can be referred to as a copy of the actual DOM representation that is
used to hold the updates made by the user and finally reflect it over to the original
Browser DOM at once consuming much lesser time.
React DOM
React provides the developers with a package react-dom a.k.a ReactDOM to access
and modify the DOM.
ReactDOM is a package that provides DOM specific methods that can be used at the
top level of a web app to enable an efficient way of managing DOM elements of the
web page. ReactDOM provides the developers with an API containing following
methods and a few more.
•render()
•findDOMNode()
•unmountComponentAtNode()
•hydrate()
•createPortal()
Pre-requisite: To use the ReactDOM in any React web app we must first import
ReactDOM from the react-dom package by using the following code snippet:
With JSX
<div>Hello Sapient</div>
Without JSX
React.createElement("div", null, "Hello Sapient");
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.
With JSX:
const myelement = <h1>I Love JSX!</h1>;
ReactDOM.render( myelement, document.getElementById('root'));
Without JSX:
const myelement = React.createElement('h1', null, 'I do not use JSX!');
ReactDOM.render( myelement, document.getElementById('root'));
Note: null indicates no attributes are passed the <h1> tag
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
Ex.
const myelement = <h1>React is {5 + 5} times better with JSX</h1>;
Embedding Expressions in JSX
We can put any valid JavaScript expression inside the curly braces in JSX
Example
const name = 'Joshi Karan';
const element = <h1>Hello, {name}</h1>; Example
function formatName(user) {
ReactDOM.render( return user.firstName + ' ' + user.lastName;
element, }
document.getElementById('root')
); const user = {
firstName: 'Harper',
We can use JSX inside of if statements lastName: 'Perez'
and for loops, assign it to variables, };
accept it as arguments, and return it
const element = (
from functions: Example <h1>
function getGreeting(user) { Hello, {formatName(user)}!
if (user) { </h1>
return <h1>Hello, {formatName(user)}!</h1>; );
}
return <h1>Hello, Stranger.</h1>; ReactDOM.render(
element,
}
document.getElementById('root')
);
JSX : HTML on multiple lines
To write HTML on multiple lines, place the HTML inside parentheses:
import React from 'react';
import ReactDOM from 'react-dom';
const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li> JSX follows XML rules, and therefore HTML elements
<li>Cherries</li> must be properly closed with />
</ul>
);
ReactDOM.render(myelement, document.getElementById('root'))
ReactDOM.render(myelement, document.getElementById('root'));
Rendering an Element into the DOM
In order to render any element into the Browser DOM, we need to have a
container or root DOM element.
It is almost a convention to have a div element with the id=”root” or id=”app”
to be used as the root DOM element.
Let’s suppose our index.html file has the following statement inside it.
<div id="root"></div>
Now, in order to render a simple React Element to the root node, we must
write the following in the App.js file and export default the function
component name or class name as shown in next slide.
Export is ES6's feature which is used to export a module(file) and use it in some other
module(file).
default Export:
default export is the convention if you want to export only one object(variable,
function, class) from the file(module).
React Component Example
1. Using a Stateless Functional Component
import React from 'react';
Stateless Functional Component in ES6
function App() {
return ( const App = () => <h1>Hello World!</h1>
<h1>Hello World!</h1> export default App;
);
}
export default App; Note: If you have a class component with only
a render method –make it a functional
2. Using a Class component.
import React from 'react';
import ReactDOM from 'react-dom';
</div>
);
}
}
ReactDOM.render(
<ExampleClass />,
document.getElementById("root")
);
this.state = {
darkTheme: False,
searchTerm: ''
};
The above definition has two attributes we can use a single setState() method
to update both together or we can use separate setState() methods to update
the attributes independently.
React internally merges setState() methods or updates only those attributes which
are needed.
Difference of Props and State
Props are immutable i.e. once set the props cannot be changed, while State is an
observable object that is to be used to hold data that may change over time and
to control the behavior after each change.
States can only be used in Class Components while Props don’t have this
limitation.
While Props are set by the parent component, State is generally updated by event
handlers.
Parent-Child Communication
Parent-to-child communication is a via props. Short for properties, props are
data that are passed from a parent to its children and are made available
through this.props on the child component.
The standard way of doing this is to have the parent pass a function
to the child through props. The child then calls this function at some point and
passes it a value that the parent is supposed to react to.
We then write the functionality for the parent's reaction inside the parent
component.
ReactJS | Lifecycle of Components
A React Class Component can go through four stages of its life as follows.
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.
Initialization: In this phase the developer has to define the props and initial state
of the component this is generally done in the constructor of the component. The
following code snippet describes the initialization process.
ReactJS | Lifecycle of Components
React have many methods or “hooks” that are called during the lifecycle of an component, which
allows us to update the UI and application state.
ReactJS | Lifecycle of Components, Initialization
1. Initialization: In this phase the developer has to define the props and initial state of
the component this is generally done in the constructor of the component. The following
code snippet describes the initialization process.
class Clock extends React.Component {
constructor(props)
{
// Calling the constructor of parent Class React.Component
super(props);
Now React follows a default procedure in the Naming Conventions of this predefined
functions where the functions containing “Will” represents before some specific
phase and “Did” represents after the completion of that phase.
Updation is the phase where the states and props of a component are updated
followed by some user events such as clicking, pressing a key on keyboard etc.
The following are the descriptions of functions that are invoked at different points
of Updation phase.
componentWillRecieveProps(newProps)
{
if (this.props !== newProps) {
console.log(" New Props have been assigned ");
// Use this.setState() to re-render the page.
}
}
ReactJS | Lifecycle of Components, Updation
setState() Function: This is not particularly a Lifecycle function and can be invoked
explicitly at any instant. This function is used to update the State of a component.
React has the same events as HTML: click, change, mouseover etc.
Adding Events
React events are written in camelCase syntax:
onClick instead of onclick.
React:
<button onClick={shoot}>Take the Shot!</button>
Event Handlers
Event handling is very important as it ensures React keeps track of every action
performed by the user. A good practice is to put the event handler as a method in the
component class
React Events
import React from 'react';
class Football extends React.Component {
//event handler
shoot() {
alert("Great Shot!");
}
render() {
return (
<button onClick={this.shoot}>Take the shot!</button>
);
}
}
If you have to use regular functions instead of arrow functions you have to
bind this to the component instance using the bind() method:
constructor(props) {
super(props)
this.shoot = this.shoot.bind(this)
}
shoot() {
alert(this);
}
Handling Events
Make this available in the shoot function by
import React from 'react'; binding it in the constructor function:
import ReactDOM from 'react-dom';
Ex.
Send "Goal" as a parameter to the shoot function, using arrow function:
Note on the second example: If you send arguments without using the bind method,
(this.shoot(this, "Goal") instead of this.shoot.bind(this, "Goal")), the shoot function will
be executed when the page is loaded instead of waiting for the button to be clicked.
Event Handling: Another Example
The following example where we will only use one component. We are just adding onClick event
that will trigger updateState function once the button is clicked.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated...'})
}
render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
export default App;
Event Handling: Another Example
Child Events
When we need to update the state of the parent component from its child, we can create an event
handler (updateState) in the parent component and pass it as a prop (updateStateProp) to the
child component where we can just call it.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated from the child component...'})
}
render() {
return (
<div>
<Content myDataProp = {this.state.data}
updateStateProp = {this.updateState}></Content>
</div>
);
}
}
Event Handling: Example-II
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div>
<input type = "text" value = {this.state.data}
onChange = {this.updateState} />
<h4>{this.state.data}</h4>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
export default App;
React Forms : Example-II
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
handleChange(event) { return (
this.setState({value: event.target.value}); <form onSubmit={this.handleSubmit}>
} <label>
Name:
handleSubmit(event) { <input type="text"
alert('A name was submitted: ' + value={this.state.value}
this.state.value); onChange={this.handleChange} />
event.preventDefault(); </label>
} <input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(<MyForm />,
document.getElementById('root'));
export default NameForm;
Lifting State Up
In a scaling application, you will notice that you pass a lot of state down to child
components as props. These props are often passed down multiple component
levels. That's how state is shared vertically in your application.
Yet, the other way around, you will notice that more components need to use and
thus share the same state. That's how state needs to be shared horizontally across
components in your component tree.
These two scaling issues, sharing state vertically and horizontally, are common in
local state management in React. Therefore you can lift the state up and down for
keeping your local state architecture maintainable.
There should be a single “source of truth” for any data that changes in a React
application. Usually, the state is first added to the component that needs it for
rendering.
Then, if other components also need it, you can lift it up to their closest common
ancestor.
To solve this, we will Lift the state of component B and component C to component A.
Lifting State Up
https://reactjs.org/docs/lifting-state-up.html
Thank You!