0% found this document useful (0 votes)
26 views67 pages

React 1 V1

React is a declarative and efficient JavaScript library for building user interfaces, allowing developers to create complex UIs from small, reusable components. It utilizes a virtual DOM for efficient updates and can be integrated with various backend technologies. The document also covers installation, creating applications, debugging, and the differences between functional and class components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views67 pages

React 1 V1

React is a declarative and efficient JavaScript library for building user interfaces, allowing developers to create complex UIs from small, reusable components. It utilizes a virtual DOM for efficient updates and can be integrated with various backend technologies. The document also covers installation, creating applications, debugging, and the differences between functional and class components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

React JS

Introduction

React is a UI library built by Facebook. React gives us the ability to


logically think about our frontend sites and apps.

React is a declarative, efficient, and flexible JavaScript library for


building user interfaces.

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.

By enforcing a clear structure (container and presentational components)


and a strict data flow (components react to state and props change) its
easier than before to create well reasoned UI logic.

The basic theory in React is that a piece of UI can "react" in response to


state changes.
React is neither MVC or notMVC. It's a library to render the View (with a lots of cool
stuff, but still). You can use either MVC patterns, or Flux/Redux, or whatever.

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

Note: Type VSCode in search box and open it VS code editor.

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.

Note: To create a production build, use npx run build.

Babel is a free and open-source JavaScript transcompiler ( in short called as


transpiler) that is mainly used to convert ES 6( ECMAScript 2015+ ) code into
a backwards compatible version of JavaScript that can be run by older
JavaScript engines
Debugging React
Debugging React
To debug the client side React code, we'll need to install the Debugger for Chrome
extension.
https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome

React Developer Tools for Chrome


Integrating Bootstrap4 into React
There are two ways of integrating Bootstrap with React.
1. Copy the CDN link into the header section of index.html
Go to the https://getbootstrap.com/docs/4.0/getting-started/introduction/
Copy CSS link and paste in head section of index.html of your React application.

2. Download Bootstrap Library


At VSCode terminal, type the following
>npm install bootstrap –save

Note: save option makes an entry into package.json


Introduction
React is a declarative, efficient, and flexible JavaScript library for building
user interfaces.

It’s ‘V’ in MVC. ReactJS is an open-source, component-based front end


library responsible only for the view layer of the application.

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.

A react application is made of multiple components, each responsible for


rendering a small, reusable piece of HTML.

Components can be nested within other components to allow complex


applications to be built out of simple building blocks.
How does React Work
While building client-side apps, a team at Facebook developers realized that
the DOM is slow.

The Document Object Model (DOM) is an application programming interface


(API) for HTML and XML documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.

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.

Adding an HTML div


We need to create an HTML div and then we can start working with React. In
the HTML panel, create a div called root or app. Naming it root or app is
standard across the React landscape since this is the main div where our React
app will take place.
That’s all we need in HTML!
Connecting index.js and index.html

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.

We have enabled html-webpack-plugin to generate the HTML file. In our


configuration, we specified that it should read public/index.html as a template.
Connecting index.js and App.js
index.js is the traditional and actual
entry point for all node apps.

Here in react, it just has code of what to


render and where to render.

App.js on the other hand has the root


component of the react app because
every view and component are handled
with hierarchy in React, where <App /> is
the top most component in hierarchy.

This gives you feel that you maintain


hierarchy in your code starting
from App.js.
React Components
What exactly is a component?
In the simplest terms, a component is comprised of:
•a template (HTML)
•interactivity (JavaScript)
•styles (CSS)
By organizing our sites and apps into components, we are able to work with
our UI as separate parts.
React Components
Every application you will develop in React will be made up of pieces called
components. Components make the task of building UIs much easier.

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.

Creating the React Component

1. Using a Stateless Functional Component

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.

In React we mainly have two types of components:

Functional Components: Functional components 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.

Below example shows a valid functional component in React:

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.

Below example shows a valid class-based component in React:

class Democomponent extends React.Component{


render(){
return <h1>Welcome Message!</h1>;
}
}
React Components
Class components are ES6 classes and Functional Components are
functions.

The only constraint for a functional component is to accept props as an


argument and return valid JSX.
The key thing that makes functional component different from a class
component is the lack of state and lifecycle methods.

This is why functional components are also commonly referred to as


stateless components.

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.

As a betterment, React brought into the scene the virtual DOM.

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:

import ReactDOM from 'react-dom'


Component render() Vs React DOM render() Function
Component.render()
A component's render() method takes no arguments and returns the corresponding React
element tree for that component. Component.render() gets called when the props or the state
of a component change and shouldComponentUpdate() returns true. Based on the new props
and state a new element React element tree is returned from the Component.render() method.
ReactDOM.render()
The ReactDOM.render(element, container) method is a top-level API that takes a React element
root of an element tree and a container DOM element as arguments. It then turns that passed
React element into a corresponding DOM element (tree) and then mounts that element as a
child in the container DOM element.
Before mounting any DOM elements to the container though, React performs a diff between
the passed element tree and the currently mounted DOM to determine which of the DOM
nodes in the currently mounted DOM have to be updated in order to match the newly passed
element tree.
React creates a virtual DOM before adding (mounting) it into the actual browser DOM,
before it is displayed. One of the two methods does the first action only, and the other
does both.
component.render only creates the virtual DOM. It does not add it to the actual browser
DOM.
ReactDOM.render does both. It creates (or updates) the virtual DOM, and then
additionally adds it to the actual browser DOM.
JSX

With JSX
<div>Hello Sapient</div>

Without JSX
React.createElement("div", null, "Hello Sapient");

Note: null indicates no attributes are passed the <div> tag

Note: Babel during transpilation will convert JSX to JS as shown above


JSX
JSX stands for JavaScript XML which allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.

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

import React from 'react';


The HTML code must be import ReactDOM from 'react-dom';
wrapped in ONE top level
element. So if you like to const myelement = (
write two headers, you <div>
must put them inside a <h1>I am a Header.</h1>
parent element, like a div <h1>I am a Header too.</h1>
</div>
element
);

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

class Test extends React.Component {


render() {
return <h1>Hello World!</h1>;
}
} Note: Use ReactDOM.render() to target the HTML element by id of
index.html.
ReactDOM.render(<Test />, document.getElementById('root'));
export default Test;
React Props
What are props?
Props is short for properties and they are used to pass data between React
components.
React’s data flow between components is uni-directional (from parent to child only).

How do you pass data with props?


Here is an example of how data can be passed by using props:
class ParentComponent extends React.Component {
render() {
return (
<ChildComponent name="First Child" />
);
}
}

const ChildComponent = (props) => {


return <p>{props.name}</p>;
};

ReactDOM.render(<ParentComponent />, document.getElementById('root'));


export default ParentComponent;
React Props
// Parent Component
class Parent extends React.Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = "5555"/>
</div>
); ReactDOM.render(
} // passing props
}
<Parent />,
// Child Component document.getElementById("root")
class Child extends React.Component{ );
render(){
return( export default Parent;
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
);
} Note: Props are read-only. We are not allowed to modify the content
}
of a prop. Whatever the type of Component is – functional or class-
based, none of them is allowed to modify their props.
defaultProps
React allows us to pass some default information using props to our components. React
provides us with something called defaultProps for this purpose.
defaultProps

The defaultProps is a class ExampleClass extends React.Component{


render(){
method which we can return(
use to store as much <div>
information as we want {/* using default prop - title */}
<h1>This is {this.props.title}'s Website!</h1>
for a particular class.
</div>
This information can be );
accessed from }
}
anywhere inside that
particular class. // Creating default props for ExampleClass Component
ExampleClass.defaultProps = {
title: "defaultProps example"
Every piece of }
information you add
inside the defaultProps ReactDOM.render(
will be added as the <ExampleClass />,
document.getElementById("root")
prop of that class. );

export default ExampleClass;


Passing arrays as props
class ExampleClass extends React.Component{
render(){
return(
<div>
{/* accessing array prop directly */}
<h1>The names of students are: {this.props.names}</h1>

</div>
);
}
}

// Passing an array as prop


ExampleClass.defaultProps = {
names: ['Ram', 'Shyam', 'Raghav']
}

ReactDOM.render(
<ExampleClass />,
document.getElementById("root")
);

export default ExampleClass;


Formatting array elements
In the previous example all class ExampleClass extends React.Component{
render(){
elements in the array are return(
displayed without any <div>
formatting. {/* iterating over array using map() */}
<h1>{this.props.names.map(
If we want to add some function namesIterator( item, i){
formatting before we print return (
an array element? Or in "Student "+ (i+1) +": " + item + ((i!=2)?', ':'\n')

other words, what if we


)
want to iterate the array }
passed as props? To do
so, we can use the map() )}</h1>
</div>
method available in );
JavaScript. }
We will have to pass a }
function as an argument to // Passing an array as prop
ExampleClass.defaultProps = {
the map() method. The names: ['Ram', 'Shyam', 'Raghav']
function will be accepting }
two parameters out of ReactDOM.render(
<ExampleClass />,
which the first one is array document.getElementById("root")
item and the second one is );
the index of the array export default ExampleClass;
items.
ReactJS | State in React
React class components have class Car extends React.Component {
a built-in state object. The constructor(props) {
super(props);
state object is where you store
this.state = {
property values that belongs brand: "Ford",
to the component. model: "Mustang",
color: "red",
When the state object changes, year: 1964
the component re-renders };
}
Creating the state Object render() {
return (
<div>
The state object is initialized in <h1>My {this.state.brand}</h1>
the constructor: <p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}
Conventions of Using State in React:
1. State of a component should prevail throughout the lifetime, thus we must first
have some initial state, to do so we should define the State in the constructor of the
component’s class. To define a state of any Class we can use the sample format below.
Class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = { attribute : "value" };
}
}
2. State should never be updated explicitly. React uses an observable object as the
state that observes what changes are made to the state and helps the component
behave accordingly. For example, if we update the state of any component like the
following the webpage will not re-render itself because React State will not be able to
detect the changes made.
this.state.attribute = "new-value";
Thus, React provides its own method setState(). The setState() method takes a single
parameter and expects an object which should contain the set of values to be updated.
Once the update is done the method implicitly calls the render() method to repaint the
page.
this.setState({attribute: "new-value"});
Note: The only time we are allowed to define the state explicitly is in the constructor to
provide the initial state.
Conventions of Using State in React:
3. React is highly efficient and thus uses asynchronous state updates i.e. React may
update multiple setState() updates in a single go. Thus using the value of current state may
not always generate the desired result. For example, let us take a case where we must
keep a count. Many developers may miswrite the code as below.

this.setState({counter: this.state.count + this.props.diff});

Now due to asynchronous processing, this.state.count may produce an undesirable result.

A more appropriate approach would be to use the following.

this.setState((prevState, props) => ({


counter: prevState.count + props.diff Using ({}) is to destructure the arguments
})); and => () is an implicit return equivalent to
=> { return ()}
In the above code we are using the ES6 thick arrow function format to take the
previous state and props of the component as parameter and are updating the counter.
The same can be written using the default functional way as follows.

this.setState(function( prevState, props){


return {counter: prevState.count + props.diff};
});
Conventions of Using State in React:
4. State updates are independent. The state object of a component may contain
multiple attributes and React allows to use setState() function to update
only a subset of those attributes as well as using multiple setState() methods
to update each attribute value independently.
For example let us take the following component state into account.

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.

Child-to-parent communication is a little more complicated.

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.

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.
ReactJS | Lifecycle of Components

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

// Setting the initial state


this.state = { date : new Date() };
}
}
ReactJS | Lifecycle of Components, Mounting
2. Mounting: Mounting is the phase of the component lifecycle when the initialization
of the component is completed and the component is mounted on the DOM and
rendered for the first time in the webpage.

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.

Mounting phase consists of two such predefined functions as described below.

componentWillMount() Function: As the name clearly suggests, this function is


invoked right before the component is mounted on the virtual DOM i.e. this function
gets invoked once before the render() function is executed for the first time.

•componentDidMount() Function: Similarly as the previous one this function is


invoked right after the component is mounted on the DOM i.e. this function gets
invoked once after the render() function is executed for the first time.
ReactJS | Lifecycle of Components, Updation
3. Updation: React is a JS library that helps create active web pages easily i.e.
pages that behave according to its user.

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() Function: This is a Props exclusive Function


and is independent of States. This function is invoked before a mounted
component gets its props reassigned. The function is passed the new set of Props
which may or may not be identical to the original Props. Thus checking is a
mandatory step in this regards. The following code snippet shows a sample use-
case.

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.

shouldComponentUpdate() Function: By default, every state or props update re-render


the page but this may not always be the desired outcome, sometimes it is desired that on
updating the page will not be repainted. The shouldComponentUpdate() Function fulfills
the requirement by letting React know whether the component’s output will be affected by
the update or not. shouldComponentUpdate() is invoked before rendering an already
mounted component when new props or state are being received. If returned false then
the subsequent steps of rendering will not be carried out. This function can’t be used in
case of forceUpdate(). The Function takes the new Props and new State as the
arguments and returns whether to re-render or not.

componentWillUpdate() Function: As the name clearly suggests, this function is


invoked before the component is re-rendered i.e. this function gets invoked once before
the render() function is executed after the updation of State or Props.

componentDidUpdate() Function: Similarly this function is invoked after the component


is re-rendered i.e. this function gets invoked once after the render() function is executed
after the updation of State or Props.
ReactJS | Lifecycle of Components
4. Unmounting: This is the final phase of the lifecycle of the component that is the
phase of un-mounting the component from the DOM. The following function is the sole
member of this phase.

componentWillUnmount() Function: This function is invoked before the component is


finally un-mounted from the DOM i.e. this function gets invoked once before the
component is removed from the page and this denotes the end of the lifecycle.
class Clock extends React.Component { // Before unmounting the Clock, Clear the interval "Timer" this step
//is a memory efficient step.
constructor(props) componentWillUnmount()
{ {
super(props); clearInterval(this.timer);
this.state = { time : new Date() }; }
}
// This function updates the state,
// invokes re-render at each second.
// As soon as the Clock is mounted. tick()
// Start the interval "timer". {
// Call tick() every second. this.setState({
componentDidMount() time : new Date()
});
{ }
this.timer = setInterval(
() => this.tick(), render()
1000); {
} return (
<div><h1>Welcome to { this.props.title } !</h1>
<h2>{this.state.time.toLocaleTimeString()}</h2></div>
);
}
} ReactDOM.render(
<Clock title="React lifecycle Demo" />, document.get
ElementById('root'));
export default Clock;
React import and export
Importing is possible only if the module or named property to be imported has been exported in
its declaration. In React we use the keyword export to export a particular module
// Importing combination import React, {Component} from 'react';
import React, {Component} from 'react'; // Importing Module
// import ReactDOM from 'react-dom';
class ChangeColor extends Component { import ChangeColor from './change-color.js';
constructor(props) // Importing CSS
{ import './index.css';
super(props);
this.state = { color : '#4cb96b' }; class App extends Component {
} render()
{
getClick() return (<div><h2>Welcome to</h2>
{ <ChangeColor title="React for all" /></div>);
if (this.state.color === '#4cb96b') }
this.setState({ color : '#aaa' }); }
else
this.setState({ color : '#4cb96b' }); ReactDOM.render(
} <App/>,
document.getElementById('root')
render() );
{
return <h1 style = { this.state } export default App;
onClick = {this.getClick.bind(this)}
>
{this.props.title} < /h1>
}
}
export default ChangeColor;
React Events
Just like HTML, React can perform actions based on user events.

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 event handlers are written inside curly braces:


onClick={shoot} instead of onClick="shoot()".

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

ReactDOM.render(<Football />, document.getElementById('root'));

export default Football;


Handling Events
For functions in React, the this keyword represents the component that owns the
method.
That is why use arrow functions. With arrow functions, this will always represents
the object that defined the arrow function.

In class components, the this keyword is not defined by default.

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

class Football extends React.Component {


constructor(props) {
super(props)
this.shoot = this.shoot.bind(this)
}
shoot() {
alert(this);
/*
Thanks to the binding in the constructor function,
the 'this' keyword now refers to the component object
*/
}
render() {
return (
<button onClick={this.shoot}>Take the shot!</button>
);
}
}

ReactDOM.render(<Football />, document.getElementById('root'));


Passing Arguments
If you want to send parameters into an event handler, you have two options:

1. Make an anonymous arrow function:

Ex.
Send "Goal" as a parameter to the shoot function, using arrow function:

import React from 'react';


import ReactDOM from 'react-dom';

class Football extends React.Component {


shoot = (a) => {
alert(a);
}
render() {
return (
<button onClick={() => this.shoot("Goal")}>Take the shot!</button>
);
}
}

ReactDOM.render(<Football />, document.getElementById('root'));


Passing Arguments
2. Bind the event handler to this.

Note that the first argument has to be this.

import React from 'react';


import ReactDOM from 'react-dom';
class Football extends React.Component {
shoot(a) {
alert(a);
}
render() {
return (
<button
onClick={this.shoot.bind(this, "Goal")}
>Take the shot!</button>
);
}
}
ReactDOM.render(<Football />, document.getElementById('root'));

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

class Content extends React.Component {


render() {
return (
<div>
<button onClick = {this.props.updateStateProp}>CLICK</button>
<h3>{this.props.myDataProp}</h3>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
export default App;
React Event Object
Event handlers have access to the React event that triggered the function.
In our example the event is the "click" event. Notice that once again
the syntax is different when using arrow functions or not.
With the arrow function you have to send the event argument manually:
import React from 'react'; Ex. Arrow Function: Sending the event object
import ReactDOM from 'react-dom';
manually:
class Football extends React.Component {
shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
render() {
return (
<button
onClick={(e) => this.shoot("Goal", e)} >Take the shot!</button>
);
}
}
React Event Object
Without arrow function, the React event object is sent automatically as the last
argument when using the bind() method:

import React from 'react';


import ReactDOM from 'react-dom';

class Football extends React.Component {


shoot(a, b) {
alert(b.type);
/*
'b' represents the React event that triggered the function, in this case the 'click' event
*/
}
render() {
return (
<button
onClick={this.shoot.bind("Goal",this)}
>Take the shot!</button>
);
}
}
ReactDOM.render(<Football />, document.getElementById('root'));
React Forms
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 of input element:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: '' };
}
myChangeHandler = (e) => {
this.setState({username: e.target.value});
}
render() { Note: e is the event, which in this case
return (
<form>
is change, target is the element that
<h1>Hello {this.state.username}</h1> triggered the event, which in this case is
<p>Enter your name:</p> the input, and value is the value of
<input
type='text' the input element
onChange={this.myChangeHandler}
/>
</form>
);
}
}

ReactDOM.render(<MyForm />, document.getElementById('root'));


export default MyForm;
React Forms : Example-1
In this example, we will set an input form with value = {this.state.data}. This allows to
update the state whenever the input value changes. We are using onChange event that
will watch the input changes and update the state accordingly.
class App extends React.Component {
constructor(props) {
super(props);

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.

Basically, it is a refactoring that you have to do once in a while to keep your


components maintainable and focused on only consuming the state that they need to
consume.
Lifting State Up
In React, sharing state is accomplished by moving it up to the closest common
ancestor of the components that need it. This is called “lifting state up”.

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.

Say we have 3 components in our application,


Where A is the parent of B and C. In this case, If there is some
Data only in component B but, component C also wants that
data. We know Component C cannot access the data
because a component can talk only to its parent or child (Not
cousins).

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!

You might also like