You are on page 1of 61

React

www.netlink.com
• Introduction
• Setup Environment
Prerequisites:-
✓ HTML
✓ CSS
✓ JavaScript
1. Unified UX
2. Fluid UX
3. Loosely Coupled & Extensible
4. Simplified Deployment & Upgrade
SPA(Single Page Application)
❑JavaScript
❑JQuery
❑Angular
❑React
Limitations of JQuery & JavaScript
➢ JS, JQ lot of DOM manipulation
➢ Lot of coding
➢ Lot of references
➢ Heavy
➢ Slow

What is solution?

➢ Better use library like React


➢ Better use Framework like Angular, Knockout.js, BackBone, Ember, Vue.
What is React JS:-
➢ React JS is a JavaScript library used in web development to build interactive elements on
websites.
➢ React is created by Facebook
➢ React is a User Interface (UI) library
➢ React is a tool for building UI components
➢ React can be used as a base in the development of single-page or mobile applications.
➢ React is only concerned with state management and rendering that state to the DOM,
so creating React applications usually requires the use of additional libraries for routing,
as well as certain client-side functionality.
➢ First version-2013 & Latest version march 2021-17.0
Component Based Modular & Asynchronous

Virtual DOM Differential Loading

Faster in rendering Reduces compatibility issues


DOM :- The DOM is basically an API for HTML and XML documents where it logically creates a structure that can be
accessed and manipulated by the browser with the help of javascript.
Shadow DOM :-
The shadow DOM is a way of encapsulating the implementation of web components. Using the shadow DOM, you
can hide the implementation details of a web component from the regular DOM tree.
Virtual DOM :-

➢ In Virtual DOM concept copy of DOM is saved in the memory


and while any change is done in the DOM, it’s compared to
find differences. Then browser knows which elements were
changed and can update only those part of the application to
avoid re-rendering all the DOM.

➢ Virtual DOM or VDOM is just a virtual representation of


the UI which is kept in the memory and synced with
Real DOM
1. Use React in existing web application.
2. Create new web application using templates.
3. Create new web application using web packs.
1.Download & Install a package Manager(
❑ NPM from “Node.js”
▪ to check node version:- node –v
▪ To check NPM version:- npm –v

https://nodejs.org/en/download/

2.Download & Install Editor


❑ “Visual Studio Code”

https://code.visualstudio.com/
React in existing web application
A typical react application requires the following tool chain:-

❑Compiler-----------------------Babel
❑Core Library-------------------React
❑Virtual DOM Library---------React
❑Web Pack
❑Rendering Engine/View
❑Testing Tool
A typical react application requires the following tool chain:-

❑Core Library-------------------React

❑Virtual DOM Library---------React

❑Compiler-----------------------Babel
✓ Open your PC locations
✓ Create a new folder for project “C:\WebApp”
✓ Open “WebApp” folder in “Visual Studio Code”
✓ Open Terminal in VS-Code

✓ Run the command


npm init -y This will generate “package.json”

✓ Add a new folder by name “src”(dynamic file)


✓ Add a new folder by name “public”(static file)
✓ Add following file into “public” folder
o Index.html
o Home.html
Creating a React Application by using “Create-React-App” library
Create-React-App” is a tool that provides commands for creating and configuring a complete react application.

Method 1--Just by using the command


npm install -g create-react-app
create-react-app AppName

Method 2-- You can also use “npx create-react-app”, which doesn’t
require to install “create-react-app” tool
npx create-react-app yourAppName
e.g. npx create-react-app react-shopping-app

npm start
React is component based.

➢ A component comprises template with presentation and logic.

➢ A pre-defined logic and presentation which you can implement and use in any application.

➢ React allows to create custom components.

➢ A component comprises of
o Presentation - HTML
o Logic - TS/JS/JSX
o Style – CSS
➢ A component is re-usable.
JSX in React Components

➢ JSX stands for “JavaScript XML”.

➢ JSX is a statically-typed object oriented programming language.

➢ It is extending JavaScript to build “Robust” application. [Large Scale Application].

➢ React is using JSX to handle interactions.

➢ However, it not mandatory to use JSX. But it simplified your JavaScript.

➢ JSX can extend HTML and make the markup dynamic.

➢ The JSX dynamic expressions are defined using “{ }”

➢ The JavaScript dynamic expression is defined using “${ }”


➢ A React component can be either “Stateful” or “Stateless."

➢ “Stateful” components are of the class type, while “Stateless” components are of
the function type.
➢ In React, function components are a way to write components that only contain a render method and don't
have their own state.

➢ They are simply JavaScript functions that may or may not receive data as parameters.

➢ We can create a function that takes props(properties) as input and returns what should be rendered.

➢ The functional component is also known as a stateless component because they do not hold or manage
state.
➢ Class components are more complex than functional components.It requires you to extend from React.

➢ Class Component create a render function which returns a React element.

➢ You can pass data from one class to other class components.

➢ You can create a class by defining a class that extends Component and has a render function. It can render
virtual DOM elements by using “render()” method.

➢ The class component is also known as a stateful component because they can hold or manage local state.

➢ Class Component is just a JavaScript class that extends “React.Component” base class.
JavaScript class comprises only
o Properties
o Methods
o Accessors
o Constructor
1. Create a file called “Class.js” and write the
following code.

2. After creating the class component,


render it into App.js file in a similar
fashion like we render
Functional Component.
Data Binding is a technique use in web applications to bind model data with the UI.

• React supports "one-way-binding".


• One way binding is a technique used to read data from source and bind to UI.
Data Binding in Object:-
Configuring State in Class Component

▪ State is defined at the time of initialization.


▪ It is configured in component constructor.
▪ In class component derived class constructor must have a super call.
▪ State in class component is configure by implementing "state" object of
"React.Component" base class.
▪ New Version(16+)All are statefull components
▪ React JS function component can use state by using a Hook "useState()".

const [refGetter, refSetter ] = useState();


Configuring State in Class Component

Syntax:
class ComponentName extends React.Component
{
constructor(props) {
super(props);
this.state = {
key : value
}
} - State key can contain any type of value: Primitive or
} Non-Primitive.
- You can access state with reference of key.

Syntax:
this.state.key
Set Value into State Object:

To set value into state object we have to use "setState()" of "React.Component" base.

• The default state of a class component is not accessible to any method in the class.
• You have to bind the methods with class in order to set state.
• Binding of method with class can be defined in various ways

a) Bind in the constructor

b) Bind in event handler Note: Binding is required


only when method is using
state. It is not required for
onKeyUp={this.MethodName.bind} other DOM manipulations.
Set Value into State Object:

Syntax : DOM Manipulations

UpdateName(event){
console.log(`Hello ! ${event.target.value}`);
}

Syntax : State

constructor()
{
this.UpdateName = this.UpdateName.bind(this);
}
React Properties in Components

➢ Every JavaScript class comprises of properties.


➢ The class properties are local and immutable.
➢ They can initialize value, which can be access by using
“this.propertyName”
➢ They will not allow to modify the value.
➢ React class properties are defined by using “props” which is a member of
“React.Component”
➢ “props” allows to dynamically change the value according to state and
situation.
props VS state
Class Binding in React

Class Binding in React


===================

➢ Binding a CSS class to HTML element.


➢ You can binding CSS class with "className" property

Syntax:

<span className="bi bi-house"> </span>


Style Binding in React

➢ Binding inline styles for HTML elements.


➢ It is done by using "style" property.
Syntax:
<div style={ {attributeName:value} } >

➢ You can't use css attributes directly, you have to configure as dynamic property using "camel case".

background-color : red backgroundColor: 'red'


width: '200px‘

➢ Multiple style attributes are defined as "JavaScript" object.

<h2 style="background-color:red; color:yellow"> </h2>

<h2 style={ {backgroundColor:'red', color:'yellow'} }> </h2>


Consuming Data from API by following methods:-
1. fetch()
2. jQuery
3. 3rd party
➢ fetch() is default window object method.
➢ It uses Ajax call to fetch data from API.
➢ It supports only GET.
➢ It will return data in Binary Format.
➢ We have to convert the data explicitly into JSON.

fetch("api url")
Syntax:
.then(response => response.json())
.then(data => {
store data, display data
})
➢jQuery provide Ajax methods to consume data from API.
➢jQuery supports all operations like GET, POST, PUT,
DELETE
➢ jQuery returns data in JSON format.
➢$.ajax()
➢$.getJSON()
Install jquery:
npm install jquery
Axios
➢ Returns data in JSON format.
➢ It supports all request methods.
➢ It uses "sync & async" techniques.
➢ It uses unblocking technique, It executes the given task along with other tasks.
➢ It handles CORS issues.
➢ It handles XSS [Cross Site Scripting Attacks]
➢ It handles multiple requests with one method.

Install axios:

npm install axios --save


➢ Lifecycle methods in ReactJS are different approaches that are used in different phases of the lifecycle of a
component.
➢ A React component in browser can be any of the following three statuses: mounted, update and unmounted.
Mounting:
Mounting is the process of creating an element and inserting it in a DOM tree. This phase has two functions or methods that
can hook up with componentWillMount() and componentDidMount().
Reacts Hooks in Function Components

➢ React 16+ version introduced Hooks into Function components


➢ React function component hooks are

▪ useToggle ▪ useLockBodyScroll ▪ usePrevious


▪ useFirestoreQuery ▪ useTheme ▪ useOnClickOutside
▪ useMemoCompare ▪ useSpring ▪ useAnimation
▪ useAsync ▪ useHistory ▪ useEffect
▪ useRequireAuth ▪ useLocation ▪ useState
▪ useRouter ▪ useParams ▪ useLocalStore
▪ useAuth ▪ useScript ▪ useHover etc.
▪ useEventListener ▪ useKeyPress
▪ useWhyDidYouUpdate ▪ useMemo
▪ useDarkMode ▪ useDebounce
▪ useMedia ▪ useOnScreen
- Context is the memory created for a component and made available for
all other components that are rendered within the context for
current component.

- Context uses DI [Dependency Injection] mechanism


- Context uses
a) Provider
b) Injector

- Provider is going to locate a value in memory.


- Injector is going to inject the value into component.
- Form provides an UI for application from where user can interact.
- It allows to view, input, edit and delete.
- React uses all HTML form elements.

Syntax:

<form onSubmit={handleSubmit}>
<input type="text" onChange={(e)=> {setName(e.target.value)}} value={Name}/>
<button type="submit"> Submit </button>
</form>
3rd Party React Forms

- Formik
- Kendo Forms
- React-Form
- NewForms
- ValueLink
- etc..

Using formik library


npm install formik --save
ReactJS Router is mainly used for developing Single Page Web Applications. React Router is used to define
multiple routes in the application. When a user types a specific URL into the browser, and if this URL path
matches any 'route' inside the router file, the user will be redirected to that particular route.

Without Routing URL :

http://www.amazon.in/electronics.aspx? category=mobiles&model=samsung&minPrice=12000 With

Routing URL:

http://www.amazon.in/electronics/mobiles/samsung/12000
• Routing uses "Ajax" calls, which allows to load content async.
• Routing allows to load new content into page without reloading the page.
• SPA uses routing technique, so that user can stay on one page and get access to everything on to
the page without navigating out of page.
• Routing makes the page fluid.
• Routing can be defined
• a) Server Side
• b) Client Side

• Server Side : routing is configured in API.


www.fakestoreapi.com/products/categories/electronics
• Client Side: Routing is configured in Client Side Library or Framework.
• [React, Angular, Vue etc.]
React routing library provides
❑ Router : It is container that configures Route Table .

❑ Route : It is used to configure every individual route in table.

❑ Switch : It is used to select exect requested route and ignore others.

❑ Link : It is used to configure a Hyperlink, but it navigates using a route path


not href.
React Routing
- Router Version 5.2
- Router Version 6.0 Latest

> npm install react-router-dom@5.2 --save

Syntax:

<Router>
<Route path="" component={} /> // outlet
</Router>

Syntax: Switch Selector

<Router>
<Switch>
<Route path="" exact component={} /> // outlet
</Switch>
</Router>
Upgrade to React Router v6
1. Uninstall route 5
> npm uninstall react-router-dom@5.2

2. Install route 6

> npm install react-router-dom

3. Route 6 Provides Browser Router Component that reduces browser compatibility issues

import {BrowserRouter} from 'react-router-dom'

<BrowserRouter>
<Router>

</Router>
</BrowserRouter>
4. Route 6 doesn't require <Switch> you have to configure all routes in "<Routes>" collection

<Routes>
<Route />
<Route />
</Routes>

5. Route 6 will not access the component it uses component element.

<Route path="" element={ <Component /> }>


Material UI:-
- Provides component library for react applications.

- It is native to react and built for react.

- It provides templates, themes, etc..

- It provides UI and UX components.

- The latest version stable is "5"


> npm install @mui/material

- The previous version is "4"


> npm install @material-ui/core
Components can be added to your application by using 2 techniques

1. Embedded Technique
Single file comprises of logic, presentation and styles.

2. Module Technique
Component can be separated into Logic, Styles and HTML files.

You might also like