React js
?
{ tntroduction, React Features, APP * Hello Works Applicaton, Introduction to JSX, Simple Appicaton using JSK
6.1 Introduction
peact is a declarative efficient and flexible JavaScript brary fr building usr interfaces Its ‘Vin MVC. Reacts
is an open-source, component-based frontend library responsible only for the view layer of the application itis
maintained by Facebook.
React uses a declarative paradigm that makes it easier to reason about your application and aims to b
efficione and flexible. It designs simple views foreach state in your application andReact will cfficiently update and
render just the right component when your data changes. The delarative view makes Yow code more predictable
et easier to debug. React application is made of multiple components, each responsible for rendering a small,
reusable piece of HTML. Components can be nested within other components 10 allow complex applications to be
built out of simple building blocks. A component may also maintain an internal state ~ for example, a TabList
ding tothe currently open tab.
ok to solve some problems that we were facing.
ye both
component may store a variable correspon
React i not a framework. Its just library developed by Facebo
earlier.
Advantages of ReactJS
fusing ReactlS:
Following are important benefits of
tg users with helpful documentation, training resources, and in-depth
+ It is user-friendly. React provides '
tutorials.
pt library, so iis easy 0 tar
# React JS is an open-sourcejavascri
nie web applications with React) asi offers high-unctionaity. It uses the JSX
© You can quickly build dyna
ows you to create an app wit
UavaScript Extension) that al
{h minimal coding.
atsare reusable, which makes easter to ‘develop and maintain your apps.
everal handy tools.
+ React provides its developers severa! uly too!
+ React’s componet
+ eats uses virtual DOM hat makes use 61 memory data-structure cache, and only the final changes are
vers DOM. This makes the app FASinternet Programming (MU) 62 React}s
‘© Youcanuse React on the client, server-side, and other frameworks as well.
4s ‘Thedataand component patterns in React optimize readability, which is useful when handling larger apps.
«You can create components of your choice by using the react component feature, The components can be reused ang
also helpful in code maintenance.
Torun React), npm need to install. Following are the steps to install npm
6.1.1 What is NPM?
1. NPM stands for Node Package Manager.
2. Itis world’s largest software registry.
3, Open-source developers from every continent use NPM to share and borrow packages, and many organizations
use NPM to manage development as well.
4. NPM consists of two main parts:
a, CLI (command line interface) isa tool for publishing and downloading packages
b. _Anonline repository that hosts JavaScript packages.
For more details and how to set-up your own NPM account one can refer https:/idocs.npmjs.com/about-npm.
6.1.2. NPM Installation
1. To publish and install packages one must have Nodes installed on the system.
2. To install Nodejs, visit https://nodejs.org/en/download/ and download the respective version as per the
requirement.
3. After installation to make sure Node,js and NPM is successfully installed on your system run the following
‘commands:
a, node -v: This should display the installed version of Nodejs.
b, mpm -v: This should display the installed version of NPM, After running the above commands one should
‘see the output attached in the snapshot belo
Sater i
Peat
‘As seen in the snapshot the NodeJs version installed is 12.184
184 and that
{individual machines depending on the which version is installed, OF NPM Is 7.7.6:This may vary on
—— llming (MU)
—— ing (MU) a secs
react features
Z
isa ovaScipt YMA extension. ISK stands for javase
1 Pi mended tse iptXML Although itis not necessary to use JSX itis
1s Components are the core of
FO of React. They ae essential when
scale projects: ntial when you are handling the code for large-
-binding : Re
neway data- - a se applies @ one-way data-binding ora unidirectional data flow. The advantage of
ais that It gives the user Better control over the application. Fux ensures the unidirectional low of data It
increases eficoncy by improving the application's Nexbility.
1, Simplicity: The JSK len Reacts simples the application,
5, Performer : React’s performance is excellent. The main reason behind it is that it uses a virtual DOM, unlike the
ther frameworks.
License: ReactJS is licensed under Facebook Inc,
1, Virtual DOM : React creates a virtual DOM, Le, in-memory data -structure cache. Only the final changes of DOM
have later updated in the browsers DOM.
4. JavaScript Expressions : |S expressions can be used in the jsx files using curly brackets, for example {}-
$21 How React JS Works ?
1, ReactJS creates a virtual DOM in memory : Instead of manipulationthe actual browser DOM, React}S creates
virtual DOM in memory, where it does necessary manipulation, before making the changes in thebrowser DOM.
1. React}$ only changes what needs to be changed : Once the virtual isupdated, React}S determines what
changes made are made to actualbrowser’s DOM and then it updates the same.
As shown in below attached snapshot we see that the component marked in red is updated, instead of
manipulating the actual DOM directly React)S updates the virtual DOM, compare changes with actual browser
DOM and only re-renders the component on actual browser DOM marked with green where data is changed.
VIRTUAL DOM REAL DOM
en
a 9 en C
@
.e following things installed:
ad)
sudio.com/download)
Tosetup a project in React we must have th
Node,s (https://nodejs.ore/en/downlo:
Visual Studio Code (https://codewisualst
OW abeesieas
Ke
——React js
6-4 Rey
See directory when own needs to create the project, open termina}
7 to direct
i bove software's traverse
2. After installing the at "
or command prompt and run : a 7
cman inside current folder. Inside that directory, it
parece alled my-app inside cur
"ute and stall Siti . The structure looks like one
a eee te ee structure and install the transitive dependencies.
will generate the initial pr
attached in below snapshot :
od
eat]
enn
ee
[eens
1 pubie
[ge rctcs
eae
elese ses)
eeressri
feet meee artes
1
fies
aromas
(Roruss:
ee
eee
aera
[atiedeee
Sieao'sve
re ary
tar
6.2.2 Project Structure
‘+ README.md : It is a markdown file that includes some helpful links and information that can help you while
learning to use CRA.
node_modules : It contains all the dependency related codes.
Package,json : It manages app dependencies that are present in our node modules, along with scripts that one
can run on app.
‘4 sitignore: Iisa Miles used to exclude files and folders from being tracked by GIT. In simpler words, it means the
Ses oF folders we do not to be committed to GIT's project repository Example: We do not want to include large
folders like node modules.
5+ public: It can be used to serve all the staticassets, such as images, svgs,
6
and fonts for our app.
e+ Itcontains all the source codes related to our app
6.2.3 Running App
In order to run the Reacts applicatio
™ averse tothe directory where projects created (cd my-app in our case)
and run:
a npm stant
‘The above command wall serve your project on hnttps://localhost:3000,
Teatensieaeltere Programming (MU)
scripts
React js
4
pects act PP with TOU emp
'e provid
helps to run the project locally "
“it comes with set of predefine
scripts:
e gest It helps in running test cases ifany f
Y for the project,
3, build:
«25 components
rovides: imi
[ optimized production build of th
1 project.
Components let you split the UL in
Pr to ini
functions. They acceptarbitrary inputs F oe
onscreen. cated pro
components can be of two types:
Teusable pi
ae eat Conceptually, components are like JavaScript
feact elements describingwhat should rape
1. Functional Component
how below where application is composed into reusable
Je of simple application
Consider the examp!yy
W_ internet Programming (MU) 6-6 React js
6.3 App “Hello World” Application
“Hello World” can be made using two ways. One is by NPM and another is by Yarn.
+ Any Application
+ NPMand Yarn are package managers that help to manage a project's dependencies. A dependency is, as it
sounds, something that a project depends on, a piece of code that is required to make the project work properly,
‘We need them because managing the project’s dependencies is a difficult task and it quickly becomes tedious,
and out of hand when the project grows. By managing the dependencies, we mean to include, un-include and
update them
+ NPM: Itisa package manager for the JavaScript programming language. Its the default package manager for the
JavaScript runtime environment Nodej. It consists of a command-line client, also called npm, and an online
database of public and paid-for private packages called the npm registry.
* Yarn :It stands for Yet Another Resource Negotiator and it is a package manager just like npm. It was
developed by Facebook and is now open-source. The intention behind developing yarn(at that time) was to fix
performance and security concerns with npm.
The lock file
+ NPM:NPM generates a‘package-lock json’ fle, The package-lock json file i a litle more complex due to a trade-
off between determinism and simplicity. Due to this complexity, the package-lock will generate the same
ode-modules folder for different npm versions. Every dependency will have an exact version number
associated with itin the package-lock file
* Yam :Yam generates a ‘yamuock’ ile. Yarn lock fles help in easy merge. The merges are predictable as wel,
because of the design of the lock file.
Any one method can follow to create app.
Using yarn- yarn create react-app appl
Using npm - npx create-react-app app2
Steps to create App “Hello World” Application using yarn
Goto cmd prompt. Go inside any directory eg, Desktop> and give the following command
C\Users\Yogesh\Desktop>yarn create react-app appS
‘The following screen will get appear:
Aer SIN asa anne ri
yarn create v1.22.16
(YAP eone trict econ
(YS Masaru att cn
[3/4] Linking dependencies.
[4/4] Building fresh packages.
Sie OE POC ea cr cea Lae PE ean Rea SETSBe -
programming (MU)
Peoast es Comers
rane
you'do this, you can’t go back!
erga
se iene
Patrons
pea visual Code editor by giving the command
cusers\Yogesh\Desktop\appS>code,
se llowing screen will appear.
Pe ae
4. Alter this, just type the following command to start yarn
CUsers\ Yogesh\Desktop\appS=yarn start
The following screen will appear.
AUER cco eeiacr secre
NISSEN GINS axe Ndr Ciel
Ehibiafaiaery is)
fPiteciseee is icins
compiled successfully!
Vou can now view apps in the browsers
Local: irae HyA pre Pues
OniYour Network: “http://192.168: 102.
React js68
W_ internet Programming (MU)
4. After opening studio code, Open file App.js
Remove default code and write following code :
fonction App)
(
return
Hello Weekd
)
expert default Apps :
Here. function component is being used. And simply Hello world is returned, After this this component must be
exported.
Index.css as well as App.css files must be removed from the same location as they are also not needed.
‘After this save the file and just reload the page, the following output will be shown :
©. > GS = O bocatn
Hello World
ets Create one more application to demonstrate propsDemo (props)
Step1: Create a folder as propsDemo inside sre folder. And Create two files as ParentComponentjs and
ChildComponentjs
‘Step2: Writea code in ParentComponentjs as follows;
{import Child Component from "/Child Component’
function ParentCompanens(){
lea
‘prop from parent component";
tetum
;
J
export default ParensComponent;
mn the above code, ParentComponent is having a variable “a" having a strin,
and this “a" variable is going to pass
{2 ChildComponentand Write a code in ChildComponentis as follows
function ChildComponent(props)
{
ont (a) = props;
retum
{a}
;
}
fespeatSebault ChildCompenens;> SS
agen roaming (vu)
Paretmenet fo “propeDennyParen Component
2 xneontWebtals fom UeeportWeb Vitae:
ine
geet M render
“eReatStietMode>
,
gcumentgetElementByld("root”)
k
iy pass a function
sla results (for example: report WebVitals(consoe.tog))
vant to start measuring performance in your app,
send tan analytics endpoint, Leam more: huips:/biulyiCRA
rpoatWebVitals
vials
step 4: Reload the page from browser and will display the output as follows:
© > SO socatho:
prop from parent component
React js
'we want to pass more than one component like from ParentComponent to ChildComponent then tag is
sed in ParentComponent js as follows:
ingot ChildComponent from "/ChildComponent";
function ParentComponent()
{
tet
op from parent component"s
ura
(
Component a = (u) />
“ Hella fom Parent Component !
“Itiv>
X
)
er fat, VarentComponent;
~~6-10
WF _ internet Programming (MU) Reacts
‘The output ofthis code is as follows
prop from parent component
Hello from Parent Component !
‘After creating the above Hello World Application, ets write some code for the output shown.
‘Step1: Create a folder as stateDemo inside src folder. And Create two files as Counter js and Countercss inside
stateDemo.
Step 2: Write code in Counters as follows:
import React, { useState } from "react";
import "/Counter.ess",
fupetion Counter()
{
setCounter(counter + 1);
‘
Jet decrementCounter =
{
setCounter(counter - 1);
hk
retum (
‘
‘
{counter}
‘
‘Decrement (-)
hi
)
export default Counter,«4 Introduction to ISX
eet et
ane ere EET
{sis nothing but JavaScript and XML. JSX allows
‘us to write HTML in React. [SX makes it easier to
al r to write and ad
alin React SX allows us to write HTML elements in JavaScript and place them in the DOM vthout .
ceeeElement() and appendChild() methods. Sx converts HTML tags into react elements “
sbantages of JSX.
+ tis faster because it performs optimization while compiling code to JavaScript.
+ isalso type-safe and most ofthe errors can be caught during compilation,
+ Itmakes it easier and faster to write templates, if you are familiar with HTML
(asidera variable declaration:
catelement = Hello World! ;
‘The above statement is neither a string nor HTML. It is |SX and it is an extension to JavaScript. JSX produces
aa ‘elements”. React uses the fact that rendering logic is inherently coupled with different UI logic: how events are
‘dled how the state changes over time, and how the data is prepared for display. React separates the logic with
‘ly coupled units called “components”.
sider a following example of use of JSX:
attane = "Yogesh Pings
“stclement = Hello, {name}
FaeDOM sender
nen,
“1 grtFlementity ll
roo)
ble “name.
ta ; of
‘above example use the curly braces to display the value of aaaReact jg
612
W_ internet Programming (MU)
Consider second example where more than one values are passed by referent
functionformatName(uset)
{
retumuser fintName +" + user. JastName:
firaName: ‘Yogesh’,
lastName: Ping
hk
‘const clement = Hell, {formatName(uscr)}!;
ReactDOM.render(clement, dacument geElementByl4(o0t);
in the above example, variable user which is constant variable which is having 2 values as firstname and
lastname. Another variable element s calling the function formatName() where “user” is passing as a Parameter. The
‘alues lke firstname and lastname can be accessed using “user” name and“ (period) operator.
ReactDOM is going to render these values on page.
Ory
oe ei
ocean
oat
oy
aia
CO eee aT
eerie Pat
Sener ee
emechtaean Ce yn
After compilation, JSX expressions be:
come rey
lor JavaScript function calls and evaluate to JavaScript objects.
Ww,ee
xen rogramming (MU) era
|
! React js
= reans that You COM Use ISK inside of term
sand return i from functions
nent
od Elements
is to be returned, then it
nore clement 5 Is needed to wrap with one container
te eset ar iner clement. The following examples
aoe
ye ™
itso
jostgpentemeac.Companent{
eer
tar
fromreacl’s
«iv?
ehl>Header
a> Content
Thiss the content!
k
}
I
cegrdefaulApps
Attributes
Custom attributes can be used in addition to regular HTML properties and attributes. When custom attribute is
‘be added, then data- prefix is used. In the following example, data-myattribute is added as an attribute
ofpdlement.
‘inponReactiom/react’;
‘lssAppestendsReact.Component{
oer)
{
Mesa
(
Sdn.
“Mteadere i>
Cmte a>
‘somevaliue">'T
in te cont
Wt Reacts
W Internet Programming (MU) 6-14
h
’
’
exporiefaulpps
6.5 _ Simple Application using JSX.
To write any simple application by adding one element (Text Box) the following two files are created
1. index{s
import Reet fromteaet
import Heactfromreaet’
importlteactDOMfrom'reactlom';
petit />;
‘constinye
ReactI0OM.rendex(myctementylocument gett tementl ytd rot
2. index.html
‘hunt lang="en">
eat App
av id "rot">
The output can be displayed by using LiveServer:
localhost3000au React js
Search Application,
i oines meet to perform this application,
«components folder. And add § files as follows:
3 “pt
a RA dnc
Hac Meslat eiacas
Pe etoyttssein
elit RG 18)
ASanesn naa
See ste
Tec
sodas
spt eat roel’
ea aust cprops)= > {retr
source src= {props.utl} type="audiolxema’] >
liv
eiportdefalt Audio Blt,
loagelteltjs
impor React from ‘react;
sehumbnail"> )5
v= "random" className="image-t
cans Tage t= (props) => ( Search something! 4
let elsname="teat-cente
imp’)
data = propsimagedata.map(ele=> )
iflprops search
console logimage block’);
laname:
uasonry"
sw)
Jels iffprops.searehf
data = props.audiodata.map(function(cle){
iffele ong’)
(cle.arworkUrl100}/>;
return
=" masonry-video-audio”
}
retumn(
{datalength= = =0?
Sorry Ther is no result found!
data}
export default Results
searchilarj
import React from ‘reacts
const divSiyhe= {
M exttransform: ‘uppercase!
teat Transform: ‘eapitalize’mming (MU)
Programming (
nee
Reacts
er
Pe ‘Tight
wt
ul function SearchBar(props){return(
gessName="inpul-group shadow-sm p-3 mb bgewhite rounded"
adv
apt pene onChonge= (props akelnpa) className='
ciopst 9
ivStyle}/>
,e"searchbat" style=
ert
iv lassNName="input-group-append">
pation onClick={ props.bilmageClick} className="bin bun-secondary shadow
fj qpratoasan”id="cearchbin">Search Images
s
euton onClick {props.btAudioClick} classiVame="bin bin-ingo shadow-
a ype"button” te
'searchbtn">Search Audio/Video
It
VideoRslt.js
inport React from ‘react’
const VideoRslt=(props)= > {return(
yh
‘“iport default VideoRslt;
Step1: Create Containers folder. And add 1 file “Search js’
Search js
‘pon React from reacts
“s#er SearchBar from './components/scarchBat’s
“vem ResuliList from '/eomponents/ResultList's
“ex default Search;
“Petdcault class Search extends React. Component
<=React j
18 is
¥ internet Programming (MUD
constructor(grope)
Jffnit Props and States
super(propsi:
this searebTutValue
this searchfor="none"s
fetchlmageData(searchValue){
= “ppt gh conta ese FRSPWobg7H!7ZA}SDMDSUS2ORT oH a 8{sercale
const ut
e)Slinit=20"s
const promise = fetch(utt
promisethen(vesponse=>{
var p= response,json()s
pahenresult=>(
this setState({imagedatarresult.data});
Jeateh(er=>{
Vecateb(er=>
console Jog(There is some error in data fetching:'ert)
»
»
4
fetchAudioData(searchValue){
‘const url ="hups:fitunes.apple.com/seareh?term=8 {searchValue}Slimit=20°;
const promise = fetch(url),
promise then(tesponse => {
var pre response jram()s
praben(tesult=>{
thin setState(audicdataesultreaulta));
onmale lop tesult is comsate
qaata = eventtarget vale
ceachimages(){
ims
this search
ihifetchlmageData(this.searchTxtValue);
|
B
searchAudio(){
| this searchfor="av"s
this fetchAudioData(this.searchTxtValue)s
}
rendes){
return (
muted textecenter PA"