0% found this document useful (0 votes)
9 views

React Master - Notes - Student copy

The document provides an overview of React, a JavaScript library created by Facebook for building user interfaces, detailing its components, history, and advantages such as easy learning, reusable components, and fast rendering. It also covers ES6 features relevant to React, including classes, arrow functions, and destructuring, as well as practical applications of React in various well-known platforms. Additionally, it explains how React utilizes a Virtual DOM for efficient updates and introduces concepts like JSX and React Hooks for improved performance and state management.

Uploaded by

reyance299
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

React Master - Notes - Student copy

The document provides an overview of React, a JavaScript library created by Facebook for building user interfaces, detailing its components, history, and advantages such as easy learning, reusable components, and fast rendering. It also covers ES6 features relevant to React, including classes, arrow functions, and destructuring, as well as practical applications of React in various well-known platforms. Additionally, it explains how React utilizes a Virtual DOM for efficient updates and introduces concepts like JSX and React Hooks for improved performance and state management.

Uploaded by

reyance299
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

With React Redux

By – Satya Priya Arya


Refreshing ES6
Frontend v/s Backend v/s Database
 The front end is the part of the website users can see
and interact with such as the graphical user interface
(GUI) and the command line including the design,
navigating menus, texts, images, videos, etc.
Examples – HTML, CSS, Java-Script, jQuery, React
 The backend, on the contrary, is the part of the website
users cannot see and interact with.
Example – C, C++, Java, Node.JS, C#
 The database used to store permanent information
Example – SQL Server, MySQL, MongoDB
What is React
 React runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
 React is a JavaScript library created by Facebook
 React is a User Interface (UI) library
 React is a tool for building UI components
History of React
 Before 2009, web browsers used JavaScript.
 JS was invented in the 1990 as a scripting language for
adding dynamic features to a web page from an HTML
file.
 React is a JavaScript library created by Facebook in 2011
 npm, a package manager for the Node.js environment,
was released in January 2010.
 Current version is 18.2.0
Why React
 Easy to learn
 Reusable components
 Fast rendering
 SEO friendly
 Strong community support
 Virtual DOM
ES6
 ES6 stands for ECMAScript 6
 ES6 is also known as ECMAScript 2015
 ECMA known as European Computer Manufacturers
Association - non-profit organization that develops
standards in computer hardware, communications,
and programming languages.
 React uses ES6
 In short ES6 is just some standards for JavaScript.
ES6 Continue…
 First we will learn some basic java sript.
 Then some new ES6 features
 Classes
 Arrow Functions
 Variables (let, const)
 Array Method (.map())
 Destructuring Arrays
 Modules
 Ternary Operator
 Spread Operator
 Multi line strings
 Default parameters
Sample HTML page with java script
 <html>
 <head>
 <script lang="javascript">
 function loadDoc(){
 document.getElementById("dynamic").innerHTML = "This is dynamic text " +
Date();
 }
 </script>
 </head>
 <body>
 <div id="demo">
 <h2>Let Java Script change this text</h2>
 <button type="button" onclick="loadDoc()">Change Content</button>
 </div>
 <div id="dynamic"></div>
 </body>
 </html>
Basics of java script
 Explain basic tags
 HTML
 Title
 Head
 Script
 Function
 Document
 Body
 Id
 H2
 Button
 Console
 Comments
 Operator (+ - * /)
Data types
 Supports 8 data types.
 String
 Number
 Bigint
 Boolean
 Undefined
 Null
 Symbol
 Object
 Supports 3 object data types.
 Object – {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
 Array - [“one”, “two”]
 Date - new Date("2022-03-25")
 All data types are dynamic
Functions
 A JavaScript function is a block of code designed to
perform a particular task
 Functions often compute a return value. The return
value is "returned" back to the "caller"
 var x = Add(40, 13);
function Add(a, b) {
return a + b;
}
 Write a program to convert Fahrenheit to Celsius
More statements
 IF
 Else
 Switch
 Loop
 Write a program to print day name from given 1 to 7
ES6 Classes
 One of the biggest addition of ES6 is classes
 Similar to used in any other languages
<html>
<body>
<script>
class Car {
constructor(name) {
this.brand = name;
}
price(){
return 100000;
}
}
const mycar = new Car("Ford");
document.write(mycar.brand);
document.write('<br/>');
document.write(mycar.price());
</script>
</body>
</html>
 Modify above script to print different price according to brand name.
ES6 Classes Inheritance
 Use extends keyword to inherit a class.
 Use super keyword to call parent constructor
 Add following class in previous example and try with
added class
Class Model extends Car {
constructor(name, mod){
super(name);
this.model = mod;
}
show (){
return this.price() + “, is has ” + this.model
}
}
ES6 Arrow Function
 It provides a more concise syntax for writing function
expressions by removing the "function" and "return"
keywords.
 // ES5
var multiply = function(x, y) {
return x * y;
}
// ES6
const multiply = (x, y) => x * y;
 Different styles
 Without parameter - multiply = () =>
 Single parameter - multiply = x =>
 More than one parameter = multiply = (x,y) =>
ES6 Variables
 Before ES6 we have only var keyword declaration
 ES6 added let and const style of variable declaration
 Problem with var is that is has function scope, not a
block scope.
 But let has block scope
 Const also has block scope. In addition it’s value can
never change.
ES6 Array method .map()
 Very useful function of ES6
 .map() method allows you to run a function on each
item in the array, returning a new array as the result.
 const myArray = ['apple', 'banana', 'orange'];
 const myList = myArray.map((item) => <p>{item}</p>)
 With index example
 list.map((currElement, index) => {});
ES6 Destructuring Arrays
 It makes very easy to working with arrays
 Old way
 Var fruits = ["Apple", "Banana"];
 Var a = fruits[0]
 Var b = fruits[1]
 Array Destructuring
 let fruits = ["Apple", "Banana"];
 let [a, b] = fruits;
 console.log(a, b);
 Object Destructuring
 let person = {name: "Peter", age: 28};
 let {name, age} = person;
 console.log(name, age);
ES6 Modules
 We can keep our JS code into a separate file
 Allow us to create modules (modular programming)
 Export and import keyword used for this purpose
 Below example shows 2 exports saved in a file mymod.js
 export var num = 50;
 export function getData(data) {
 //long calcuation
 };
 Use above modules in new file
 import { name, getData } from "./mymod.js";
ES6 Ternary Operator
 Simplified version of if/else statement
 Exactly same as C language
 Codition ? True : false
ES6 Spread Operator
 One more helpful operator
 Used to quickly copy all or part of an existing array or object into another array
or object
 In old version we use array1.concat(array2) to concatenate 2 arrays.
 Let’s try with new way of ES6
 const numbersOne = [1, 2, 3];
 const numbersTwo = [4, 5, 6];
 Check output of following statements.
 const numbersCombined = [...numbersOne, ...numbersTwo];
 const [one, two, ...rest] = numbersCombined;
 Difference between – Explain with push an element after creating array2 and
then print both array.
 Let array2 = array1
 Let array2 = […array1]
 Difference between – after defining let arr = ['a','b'];
 let arr2 = [arr,'c','d'];
 let arr2 = [...arr,'c','d'];
ES6 Multi line strings
 We can can create multi-line strings by using back-
ticks(`)
 let greeting = `Hello World,
 Greetings to all,
 Keep Learning and
 Practicing!`
ES6 Default parameters
 Default parameters simplified in ES6
 In ES5
 Var output = Add(a, b) {
 a = a || 100
 b = b || 200
 }
 In ES6
 Var output = Add(a = 100, b = 200) {
 }
Iterators
 A process that is repeated more than one time by applying the same logic is
called an Iteration.
 The following values are iterable:
 Arrays
 Strings
 Maps
 Sets
 If the loop is executed 6 times continuously, then we could say the particular
block has iterated 6 times.
 An iterator is an object that can access one item at a time from a collection
while keeping track of its current position
 It just requires that you have a method called next() to move to the next item
to be a valid iterator
 The result of next() is always an object with two properties –
 Value: The value in the iteration sequence
 Done: true | false
Iterator example
 Old way
 let ranks = [1,2,3,4,5];
 for (let index = 0; index < ranks.length; index++) {
 console.log(ranks[index]);
 }
 New way
 let ranks = [1,2,3,4,5];
 for (let key in ranks) {
 console.log(key);
 }
 The Symbol.iterator is a special-purpose symbol made especially for accessing an object's internal
iterator
 let ranks = [1,2,3];
 let iterator = ranks[Symbol.iterator]();
 console.log(iterator.next());
 console.log(iterator.next());
 console.log(iterator.next());
 console.log(iterator.next());
 Validate the output of above function
Generators
 Generators are a special type of function in JavaScript
that can pause and resume state.
 A Generator function returns an iterator, which can be
used to stop the function in the middle, do something,
and then resume it whenever.
 Generator functions are written using the function*
syntax
 function *generator() { // ... }
 yield is an operator with which a generator can pause
itself
Generator example
 function* stringGenerator() {
 yield 'hi 1';
 yield 'hi 2';
 yield 'hi 3';
 }
 const strings = stringGenerator();
 console.log(strings.next());
 console.log(strings.next());
 console.log(strings.next());
 console.log(strings.next());
 Validate the output of above function
Getting started React
Practical Application
 We have lots of applications created in React
 Few examples are:
 Facebook
 Netflix
 Yahoo Mail
 BBC
 Cloudflare
 Trello
 Skyscanner
 Codecademy
 Dropbox
 Flipboard
 Scribd
 Asana
Why need React
 React is Easier to Learn Compared to Angular
 React is an elementary and lightweight library that only deals with the view
layer of a web page.
 It has an easy learning curve
 If you have a functional understanding of HTML-CSS and a basic
understanding of programming concepts, you can quickly start working with
React.
 There are extensive documentation available online that will help you with
everything related to ReactJS.
 React Has a Large Development Community
 React is an open-source library
 It has amassed a massive following of JavaScript developers who develop new
solutions and tools regularly.
 A lot of user-developed applications have been included in the official library.
 You can get access to a large community of experts to solve any problems.
 React has more than 201K stars on Github and around 10 million npm
downloads weekly.
Why need React
 React Offers Reusable Components
 Components in ReactJS are independent, reusable bits of code.
 You can use them as a primary JavaScript function or a class component
 Each React component that you have developed can be reused in other parts of the app
 Virtual DOM
 Document Object Model or DOM is an interface that represents HTML and XML code
into trees.
 A web browser creates a DOM-like model to render output, treating each object/element
of the HTML code as a node in the DOM tree.
 Whenever a change occurs in the HTML code, either by user interaction or value updates,
the DOM tree has to be rendered again, leading to a lot of time and power consumption.
 ReactJS use of Virtual DOMs.
 React simply creates a copy of the DOM, maintaining a cache memory of sorts. Every time
a change is made, it examines the Virtual DOM and pinpoints exactly which tree nodes
and components need to be updated.
 With just a small change in the DOM, the tree can be updated quickly and efficiently. This
saves developers a ton of time and makes the application remarkably fast and responsive.
Why need React
 JSX increases the performance and efficiency of ReactJS
 JSX or JavaScript XML is a syntax extension for JavaScript.
 Facebook developed it to extend the functionalities of HTML
structures into JavaScript.
 With JSX, there is no requirement for separate HTML and JS codes.
 JSX, along with the Virtual DOM, increases the performance and
efficiency of ReactJS apps.
 React Hooks
 Hooks is an independent feature introduced in ReactJS 16.8
that enables JavaScript developers to write states and other features
in function components.
 You don’t need to deal with the complicated classes anymore. Using
Hooks, you can easily manage state logic between components and
share data with components without props and classes.
How React Works
 When the app first starts, there is nothing in the Virtual DOM and the real DOM.
 As a result, the set of instructions supplied to ReactDOM must include instructions for
creating everything from the start.
 However, when we interact with the user interface, such as by clicking a button, the
application state is modified.
 The state variable is changed programmatically to include specific new or altered entries.
 However, in the further steps, the importance of the Virtual DOM becomes more
prominent.
 When a Component’s state value changes, React calls the Component’s render() function
again.
 Similarly, as previously, invoking render() will produce a tree of Elements.
 This time, the tree will incorporate a new Element to symbolize the new objects.
 React now has an old tree that describes what it currently looks like and a new tree that
represents how the updated page should look.
 React must now compare these two trees and provide ReactDOM with instructions to
sync anything that has changed, which results in adding items to the UI.
 This is How React works.
Leveraging Virtual DOM
 DOM
 The DOM represents the UI of your application. Every time there is a change in the state of your
application UI, the DOM gets updated to represent that change. Now the catch is frequently
manipulating the DOM affects performance, making it slow.
 Why DOM manipulation slow
 The DOM is represented as a tree data structure. Because of that, the changes and updates to the DOM
are fast. But after the change, the updated element and it’s children have to be re-rendered to update the
application UI. The re-rendering or re-painting of the UI is what makes it slow.
 Virtual DOM
 The virtual DOM is only a virtual representation of the DOM. Every time the state of our application
changes, the virtual DOM gets updated instead of the real DOM.
 Why Virtual DOM faster
 When new elements are added to the UI, a virtual DOM, which is represented as a tree is created. Each
element is a node on this tree. If the state of any of these elements changes, a new virtual DOM tree is
created. This tree is then compared with the previous virtual DOM tree.
 Once this is done, the virtual DOM calculates the best possible method to make these changes to the
real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the
performance cost of updating the real DOM.
 In React every UI piece is a component, and each component has a state. When the state of a
component changes, React updates the virtual DOM tree. Once the virtual DOM has been updated,
React then compares the current version of the virtual DOM with the previous version of the virtual
DOM. Once React knows which virtual DOM objects have changed, then React updates only those
objects, in the real DOM. This makes the performance far better when compared to manipulating the
real DOM directly. This makes React standout as a high performance JavaScript library.
Setting up React
 Install Node.JS from (It provides JavaScript runtime)
https://nodejs.org/
 Install Visual Studio Code from
https://code.visualstudio.com/download
 npx create-react-app reactapp
 cd reactapp
 Npm start
JSX
Elements
What is JSX
 JSX stands for JavaScript XML.
 It allows us to write HTML in a React application.
 JSX allows us to write HTML elements in JavaScript.
 If you are familiar with HTML, then its very easy to
learn JSX.
 We can create React application without JSX also, but
JSX makes it very easy to write React code.
 JSX is an extension of the JavaScript language based on
ES6, and is translated into regular JavaScript at
runtime.
Code without JSX
 Replace entire index.js with below code:
 import React from 'react';
 import ReactDOM from 'react-dom/client';
 const myElement = React.createElement(
‘div’,
{style: {color:green}},
'I am not using JSX!');
 const root =
ReactDOM.createRoot(document.getElementById('root'));
 root.render(myElement);
Code with JSX
 Replace entire index.js with below code:
 import React from 'react';
 import ReactDOM from 'react-dom/client';
 const myElement = <div style=“color:green”>I am
using JSX!</div>;
 const root =
ReactDOM.createRoot(document.getElementById('ro
ot'));
 root.render(myElement);
Default app
 A default react application contains thousands of files
and folders. And its total size is approximately 100 to
200 MB.
 To transfer or send application to another use delete
node_modules folder.
 If your application doesn’t contains node_modules
folder then use command “npm install” to install
modules from package.json file.
 Using “npm install” command your application will be
ready to run again.
Folder and Files structure
 Restore to original template file structure
Understand default folder and files
structure
 Node_modules folder
 This folder contains all dependency/packages for current project. We rarely modify this folder.
 Public folder
 We will discuss this later.
 Src folder
 We will discuss this later.
 .gitignore file
 Used for Git repository. Files and folder mentioned into this files are not pushed into Git. Example
node_modules folder
 Package-lock.json file
 Every installed package is tracked in a package-lock.json file so that a product may be re-created exactly
as it was before its maintainers make any updates. We don’t modify this file generally.
 Package.json file
 This contains metadata information about the project. Metadata means name of project, version,
packages required for this project, and few scripts like start and build. We don’t modify this file
generally.
 README.md file
 This file can be used to define usage, build instructions, summary of project, etc. It uses markdown
markup language to create content.
Public folder and clean files

 Favicon.ico - Icon before page title (delete this)


 Logoxxx.png – React logos for default template (delete this)
 Manifest.json – Mostly contains metadata (delete this)
 Robots.txt – Defines rules for crawlers, scrappers. (delete this)
 Index.html – Main page to render. Clean-up everything except
“root” div.
 After clean-up we will have only index.html in public folder with
only root div.
Src folder

 App.test.js and setupTests.js – to setup test and run them


(delete these)
 Logo.svg - fefault template logo (delete this, also remove
reference from app.js)
 reportWebVitals.js – to capture user experience of web
page (delete this, also remove reference in index.js)
Src folder continue…
 App.css and app.js
 A template of a sample component
 Let’s discuss basic app.css
 Import app.css into app.js and use of classes
 Understand class vs className
 Index.css and index.js
 A template to use App component
 StrictMode is a React Developer Tool, primarily used to
identify potential issues in a web application
Create a new component
Use that component
Assignment Objective
 Create a new component called “Demo”
 This Demo should have html elements like text,
button, checkbox, paragraph, etc.
 All above html elements must have some style
attached like align, colour, size, etc..
 Use this component “Demo” into index.js
Assignment Solution
 function Demo(){
 return (
 <div>
 Hello this is a text box:
 <input type="text" name="abc"></input><br/>
 And this is button
 <input type="button" name="def"
value="Click me"></input>
 </div>
 )
 }

export default Demo;
Continue JSX
 Everything inside root div manged by
React DOM
 Work in index.js only (no components)
 Very basic example –
 root.render(<h1>Hello, world!</h1>);
 Using variables –
 const element = <h1>Hello, worlds!</h1>;
 root.render(element);
 Embedding Expressions in JSX –
 const name = 'Boys';
 const element = <h1>Hello, {name}</h1>;
Embedding expressions in JSX
 const user = {
 firstName: ‘Satya',
 lastName: ‘Arya'
 };
 function formatName(user) {
 return user.firstName + ' ' + user.lastName;
 }
 const element = (
 <h1>
 Hello, {formatName(user)}!
 </h1>
 );
JSX is an expression too (like inside
if else).
 const user = {
 firstName: ‘Satya',
 lastName: ‘Arya'
 };
 function formatName(user) {
 return user.firstName + ' ' + user.lastName;
 }
 function getGreeting(user) {
 if (user) {
 return <h1>Hello, {formatName(user)}!</h1>;
 }
 return <h1>Hello, Stranger.</h1>;
 }
 const element = (
 <h1>
 Hello, {getGreeting(user)}
 </h1>
 );
 const element = (
 <h1>
 Hello, {getGreeting()}
 </h1>
 );
Attributes with JSX
 Simple statement –
 const element = <img
src="https://www.jecrc.com"></img>;
 With attributes –
 const element = <img src={user.url}></img>;
Components and properties
 Function is a component in React
 Create a welcome component and use 3 times in index.js
 function Welcome(props) {
 return <h1>Hello, {props.name}</h1>;
 }
 const element = (
 <div>
 <Welcome name="First" />
 <Welcome name="Second" />
 <Welcome name="Third" />
 </div>
 );
Component as separate file
 Component should reside in a separate js file.
 Create Welcome.js and move component in it.
 function Welcome(props) {
 return <h1>Hello, {props.name}</h1>;
 }
 export default Welcome;
 Now use this component in code
Nested components
 Modify welcome component and use Greet component.
 Greet component
 function Greet(name){
 return 'Hello ' + name + ' . How are you doing
today?'
 }
 export default Greet;
 Welcome component
 import Greet from "./Greet";
 function Welcome(props) {
 const name = Greet(props.name);
 return <h1>{name}</h1>;
 }
 export default Welcome;
Convert component type
 To convert function component to class component do following
 Create an ES6 class, with the same name, that extends React.Component.
 Add a single empty method to it called render().
 Move the body of the function into the render() method.
 Replace props with this.props in the render() body.
 Delete the remaining empty function declaration.
 Function component
 function Welcome(props) {
 return <h1>Hello, {props.name}</h1>;
 }
 Equivalent class component
 class Welcome extends React.Component {
 render() {
 return <h1>Hello, {this.props.name}</h1>;
 }
 }
Create nested function component
Create nested class component
Assignment objective
 Create a “Display” component who will accept a object called “user”.
This user object contains keys – Name, Salary, age
 This display component display all 3 props in separate line with proper
prefix text
 If salary printed depends on salary range. It will call another
component “FormatSalary”.
 This FormatSalary print salary in
 Green colour if salary is more than 100000
 Yellow colour if salary is less than 100000 but greater than 40000
 Red colour otherwise
 Main index component will call Display component 5 times with 5
different users.
 After every user print, a line break should display.
 Create and use css file is required
 Finally convert function components into class components.
Assignment Solution
 FormatSalary.css
 .high {
 color: green;
 }
 .medium {
 color: yellow;
 }
 .low {
 color: red;
 }

 FormatSalary.js
 import './FormatSalary.css';
 function FormatSalary(salary){
 if (salary > 100000){
 return <p className='high'>{salary}</p>
 }
 else if (salary >= 40000){
 return <p className='medium'>{salary}</p>
 }
 else{
 return <p className='low'>{salary}</p>
 }
 }
 export default FormatSalary;
Assignment Solution
 Display.js
 import FormatSalary from './FormatSalary';

function Display(props) {
 const salary = FormatSalary(props.user.salary);
 return (
 <p>
 <p>User name is: {props.user.name}</p>
 <p>User Salary is: {salary}</p>
 <p>User age is: {props.user.age}</p>
 </p>
 )
 }

export default Display;
Assignment Solution
 Index.js (for one user only)
 const user = {
 name: "JECRC Student",
 salary: 200000,
 age: 20
 }
 const element = (
 <div>
 <Display user={user} />
 </div>
 );
 root.render(element);
State management
 State is similar to props, but it is private to component and
fully managed and controlled by component itself.
 Functional components doesn’t support states, but with
help of hooks we can add states (extra functionality).
 Only class components supports states.
 React components has a built-in state object.
 The state object is where you store property values that
belongs to the component.
 When the state object changes, the component re-renders.
Using states in class component
 Define state in constructor
 constructor(props) {
 super(props);
 this.state = {key: “value"};
 }
 Use state
 {this.state.key}
 We can define multiple state key value pairs.
 this.state = {
 brand: "Ford",
 model: “2023",
 color: "red"
 };
Props v/s States
 Props are immutable i.e. once set the props cannot
be changed, while State is to be used to hold data
that may change over time and to control the
behavior after each change.
 States can be used in Class Components,
Functional components with the use of React Hooks
(useState and other methods) while Props don’t
have this limitation.
 While Props are set by the parent component, State
is generally updated by event handlers.
Update State
 States can’t be updated explicitely like
this.state.attribute = “new-value”
 We must have to use setState method like
this.setState({attribute: “new-value”})
 Example: (partially code snippet)
 this.state = {brand: “Ford”}
 changeBrand = () => {this.setState({brand: “blue”});
 <p>{this.state.brand}</p>
 <button type=“button” onClick={this.changeBrand}
Change color </button>
Initialize state
Update state
Assignment objective
 Create a class component. Define 2 separate states
“name” and “salary”. Initial values will be “Demo” and
“100000”.
 Show name and salary in separate line with
appropriate prefix text.
 Add 2 buttons next to salary “increment” and
“decrement”.
 On click on increment button, salary should increased
by 1000 and on click on decrement, salary should
decreased by 1000
Create simple input form
 Create a class component and create signup html form
in it which will accept
 Name
 Password
 Submit button
 On submit button take following actions
 If Name is less than 5 character then show alert
 If password is less than 8 character then show alert
 If all ok, display name and password in console
Solution
 render () {
 return (
 <form>
 <h2>Sign up</h2>
 <div>
 <label>Name</label>
 <input type=”text” name=”name” />
 </div>
 <div>
 <label>Password</label>
 <input type=”password” name=”password” />
 </div>
 <button type=”submit”>
 Sign up
 </button>
 </form>
 )
 }

 Try to run above form and observe reload on submit button click
Validate form using state
 Setup states
 constructor (props) {
 super(props);
 this.state = {
 name: '',
 password: ''
 }
 }
 Bind control with this states
 value={this.state.email} and value={this.state.password}
 Now observe behaviour when we try to type anything
in text boxes.
Validate form using state
 Bind change event
 onChange={(event) => this.handleUserInput(event)}
 Define handleUserInput method
 handleUserInput (e) {
 const name = e.target.name;
 const value = e.target.value;
 this.setState({[name]: value});
 console.log(name, value); //Check this
 }

 Try to run above form


Adding error messages
 Create Form.css
.error {
 border-color: red;
}
 .ok {
 border-color: green;
}
 Use .error class in to Form.js
Dynamic class
 Add 2 more states in constructor
 validName: false,
 validPassword: false
 Update states in handleUserInput
 if(name == "name"){
 this.setState({validName: value.length>5});
 }
 if(name == "password"){
 this.setState({validPassword: value.length>8});
 }
 Update class name in controls
 className = { this.state.validName ? "ok" : "error" }
 className = {this.state.validPassword ? "ok" : "error"}
Submit form
 Bind form submit event
 <form onSubmit={this.submit}>
 Define submit function
 submit = (e) => {
 e.preventDefault();
 if(!this.state.validName || !this.state.validPassword){
 alert('Invalid form');
 }
 else{
 alert('Valid form');
 }
 }
Assignment
 Create 2 component
 Valid
 Invalid
 Display Valid component when there is no errors in
form else display Invalid component (without click on
butoom)
Use backend API in react app
Consume API in react app
 We can use either functional or class component
 Steps:
 Use componentDidMount method in class component
or useEffect in functional component
 Use fetch method in it
 fetch(url)
 .then(response => response.json())
 .catch(err => console.log(err))
 Either use setState or hooks state to assign a variables
with result
 Bind controls with that variables.
Code in functional component
 import { useState, useEffect } from "react";

 function MyComponent() {
 const [error, setError] = useState(null);
 const [isLoaded, setIsLoaded] = useState(false);
 const [items, setItems] = useState([]);

 useEffect(() => {
 fetch("https://reqres.in/api/users")
 .then(res => res.json())
 .then(
 (result) => {
 setIsLoaded(true);
 setItems(result.data);
 },
 (error) => {
 setIsLoaded(true);
 setError(error);
 }
 )
 }, [])

 if (error) {
 return <div>Error: {error.message}</div>;
 } else if (!isLoaded) {
 return <div>Loading...</div>;
 } else {
 return (
 <ul>
 {items.map(item => (
 <li key={item.id}>
 {item.first_name} {item.last_name}
 </li>
 ))}
 </ul>
 );
 }
 }

 export default MyComponent;


Code in class component
 import React from "react";
 class MyComponent1 extends React.Component {
 constructor(props) {
 super(props);
 this.state = {
 error: null, isLoaded: false, items: []
 };
 }
 componentDidMount() {
 fetch("https://reqres.in/api/users")
 .then(res => res.json())
 .then(
 (result) => {
 this.setState({
 isLoaded: true, items: result.data
 });
 },
 (error) => {
 this.setState({
 isLoaded: true, error
 });
 }
 )
 }
 render() {
 const { error, isLoaded, items } = this.state;
 if (error) {
 return <div>Error: {error.message}</div>;
 } else if (!isLoaded) {
 return <div>Loading...</div>;
 } else {
 return (
 <ul>
 {items.map(item => (
 <li key={item.id}>
 {item.first_name} {item.last_name}
 </li>
 ))}
 </ul>
 );
 }
 }
 }
 export default MyComponent1;
Assignment
 Include user avatar in above 2 components
 Break down one user in a separate component
Assignment Solution
 Create a new component
 function UserCard(props){
 return (
 <p>
 <img src={props.avatar} /><br/>
 {props.fname}<br/>
 {props.lname}
 </p>
 );
 }
 export default UserCard;
 Comments this line
 {item.first_name} {item.last_name}
 Add component
 <UserCard fname={item.first_name} lname={item.last_name}
avatar={item.avatar} />
React Route
 Until now we are working with one page only.
 Q: How to navigate to another page?
 A: With help of react route
 By default index.html and index.js play main role in a
react app.
 We need to setup route (by default not available with
create-react-app)
Implement Route
 Install route package
 npm install react-router-dom
 Create few pages
 Homes
 Blogs
 Contact
 Create additional page for 404
 NoPage
 Create one more page for layout
 Layout
Implement Route
 Layout of Home, Blog, Contact pages
 const PageName= () => {
 return <h1>Home</h1>;
 };
 export default PageName;
 Layout of NoPage page
 Similar to above but something not found image
Implement Route
 Layout page
 import { Outlet, Link } from "react-router-dom";
 const Layout = () => {
 return (
 <>
 <nav>
 <ul>
 <li>
 <Link to="/">Home</Link>
 </li>
 <li>
 <Link to="/blogs">Blogs</Link>
 </li>
 <li>
 <Link to="/contact">Contact</Link>
 </li>
 </ul>
 </nav>

 <Outlet />
 </>
 )
 };

 export default Layout;


Layout page
 <Link> is used to set the URL and keep track of
browsing history.
 The <Outlet> renders the current route selected.
Update index.js
 We wrap our content first with <BrowserRouter>.
 Then we define our <Routes>. An application can have
multiple <Routes>. Our basic example only uses one.
 <Route>s can be nested. The first <Route> has a path of /
and renders the Layout component.
 The nested <Route>s inherit and add to the parent route.
So the blogs path is combined with the parent and
becomes /blogs.
 The Home component route does not have a path but has
an index attribute. That specifies this route as the default
route for the parent route, which is /.
 Setting the path to * will act as a catch-all for any
undefined URLs. This is great for a 404 error page.
Complete Code
 import ReactDOM from "react-dom/client";
 import { BrowserRouter, Routes, Route } from "react-router-dom";
 import Layout from "./pages/Layout";
 import Home from "./pages/Home";
 import Blogs from "./pages/Blogs";
 import Contact from "./pages/Contact";
 import NoPage from "./pages/NoPage";

 export default function App() {


 return (
 <BrowserRouter>
 <Routes>
 <Route path="/" element={<Layout />}>
 <Route index element={<Home />} />
 <Route path="blogs" element={<Blogs />} />
 <Route path="contact" element={<Contact />} />
 <Route path="*" element={<NoPage />} />
 </Route>
 </Routes>
 </BrowserRouter>
 );
 }

 const root = ReactDOM.createRoot(document.getElementById('root'));


 root.render(<App />);
Redux
Cookies
 JavaScript cookies are small pieces of data that are
stored on a user's computer by a website.
 They are used to remember
 User preferences
 Login information
 Shopping cart contents
 and other types of data that can be useful to store across
multiple visits to the same website.
How Cookies Works?
 When a user sends a request to the server, then each of
that request is treated as a new request sent by the
different user.
 So, to recognize the old user, we need to add the
cookie with the response from the server.
 browser at the client-side.
 Now, whenever a user sends a request to the server, the
cookie is added with that request automatically. Due to
the cookie, the server recognizes the users.
How cookies work
Cookies Create
 Create a cookie in JavaScript:
 document.cookie = "name=value; expires=date;
path=path";
 The "name" parameter is the name of the cookie
 The "value" parameter is the value of the cookie.
 The "expires" parameter is the expiration date of the
cookie (Default is 14 days)
 The "path" parameter is the path of the cookie.
Cookies create
 Example, to create a cookie that expires in one hour
 var d = new Date();
 d.setTime(d.getTime() + (1 * 60 * 60 * 1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie =
"useremail=satypariyaarya@university.com; " + expires +
"; path=/";
Read a cookie
 let x = document.cookie;
 document.cookie will return all cookies in one string
much like: cookie1=value; cookie2=value;
cookie3=value;
 We have to split cookies with character “;” to read a
cookie
Example
 function setCookie(cname, cvalue, exdays) {
 const d = new Date();
 d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
 let expires = "expires="+d.toUTCString();
 document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
 }

 function getCookie(cname) {
 let name = cname + "=";
 let ca = document.cookie.split(';');
 for(let i = 0; i < ca.length; i++) {
 let c = ca[i];
 while (c.charAt(0) == ' ') {
 c = c.substring(1);
 }
 if (c.indexOf(name) == 0) {
 return c.substring(name.length, c.length);
 }
 }
 return "";
 }

 function checkCookie() {
 let user = getCookie("username");
 if (user != "") {
 alert("Welcome again " + user);
 } else {
 user = prompt("Please enter your name:", "");
 if (user != "" && user != null) {
 setCookie("username", user, 365);
 }
 }
 }
 <body onload="checkCookie()"></body>
What is Redux
 Redux is a state management library.
 We need to install this package before use.
 This is not a required package to state management,
but preferred for medium to big application.
 To use redux package install it first:
npm install redux react-redux
 It’s extremely lightweight (approximately 2KB in size)
Why use Redux
 Props can be passed from one component to another
but read only.
 States can’t be passed from one component to another
but writable.
 Using combination of props and states we can manage
states, but passing data in child element (deeper
hierarchy) is difficult to maintain.
 With Redux we have a centralized store to maintain
state of application.
Without Redux
Redux Architecture
With Redux
Redux explained
 There are three core components in Redux:
 actions
 store
 reducers
Redux actions
 Redux actions are events.
 They are the only way you can send data from your
application to your Redux store. The data can be from user
interactions, API calls, or even form submissions.
 Actions are plain JavaScript objects that must have
 a type property to indicate the type of action to be carried
out, and
 a payload object that contains the information that should
be used to change the state.
 Actions are created via an action creator, which in simple
terms is a function that returns an action. And actions are
executed using the store.dispatch() method which sends
the action to the store.
Redux actions continue
 Example of action:
 {
 type: "LOGIN",
 payload: {
 username: "foo",
 password: "bar"
 }
 }
 Example of action creator:
 const setLoginStatus = (username, password) => {
 return {
 type: "LOGIN",
 payload: {
 username,
 password
 }
 }
 }
Redux reducers
 Reducers are pure functions that take the current state of an application, perform an action, and return a new state.
 Example of reducers:
 const LoginComponent = (state = initialState, action) => {
 switch (action.type) {

 // This reducer handles any action with type "LOGIN"


 case "LOGIN":
 return state.map(user => {
 if (user.username !== action.username) {
 return user;
 }

 if (user.password == action.password) {
 return {
 ...user,
 login_status: "LOGGED IN"
 }
 }
 });
 default:
 return state;
 }
 };
Redux store
 The store is a “container” (really a JavaScript object)
that holds the application state.
 Redux allows individual components connect to the
store and apply changes to it by dispatching actions.
 It is highly recommended to keep only one store in any
application.
 Example to create a store:
 const store = createStore(LoginComponent);
Redux in action - Install
 npm install redux react-redux
Redux in action - store
 Create a Redux store in a file called store.js:

 import { createStore } from 'redux';

 // Define the initial state of the store


 const initialState = {
 count: 0,
 };

 // Define a reducer function to handle actions


 function reducer(state = initialState, action) {
 switch (action.type) {
 case 'INCREMENT':
 return { ...state, count: state.count + 1 };
 case 'DECREMENT':
 return { ...state, count: state.count - 1 };
 default:
 return state;
 }
 }

 // Create the Redux store


 const store = createStore(reducer);

 export default store;


Redux in action - provider
 Wrap your top-level component with the Provider component from react-
redux and pass the Redux store as a prop: (index.js)

 import React from 'react';


 import ReactDOM from 'react-dom';
 import { Provider } from 'react-redux';
 import store from './store';
 import App from './App';

 ReactDOM.render(
 <Provider store={store}>
 <App />
 </Provider>,
 document.getElementById('root')
 );
Redux in action - connect
 Connect your component to the Redux store using the connect function (Counter component as Counter.js)

 import React from 'react';


 import { connect } from 'react-redux';

 function Counter({ count, increment, decrement }) {


 return (
 <div>
 <p>Count: {count}</p>
 <button onClick={increment}>+</button>
 <button onClick={decrement}>-</button>
 </div>
 );
 }

 function mapStateToProps(state) {
 return {
 count: state.count,
 };
 }

 function mapDispatchToProps(dispatch) {
 return {
 increment: () => dispatch({ type: 'INCREMENT' }),
 decrement: () => dispatch({ type: 'DECREMENT' }),
 };
 }

 export default connect(mapStateToProps, mapDispatchToProps)(Counter);


Redux - Explain
 Install Dependencies: We start by installing the required dependencies for using Redux with React,
which are react, redux, and react-redux.

 Create Redux Store: Next, we create a Redux store using the createStore function from Redux. The
store holds the application's state, and we define a reducer function counterReducer to handle state
updates based on different action types. In this example, we have a simple counter state with an initial
value of 0.

 Create React Components: We create a React component called Counter that represents a counter
display with buttons for incrementing and decrementing the counter value. This component uses the
connect function from react-redux to connect to the Redux store and access the counter value from
the Redux state as a prop. We also define mapStateToProps and mapDispatchToProps functions to
map the Redux state and actions to the component props, respectively. mapStateToProps maps the
counter value from the Redux state to the counter prop, and mapDispatchToProps maps the
increment and decrement actions to the corresponding dispatch functions.

 Connect Root Component to Redux Store: We create a root component called App that wraps the
Counter component with the Provider component from react-redux. The Provider component makes
the Redux store available to all child components, including Counter, so they can access the Redux
state and dispatch actions.

 Render Root Component: Finally, we render the App component in the index.js file using
ReactDOM.render, which renders the App component inside the root element in the HTML file.
Redux in action - Finish
 Now you can use the Counter component in your app
and it will be connected to the Redux store. When you
click the "+" or "-" buttons, the increment or
decrement functions will dispatch actions to the store,
causing it to update and trigger a re-render of the
component with the new state.
Testing react app
 Software development is incomplete without quality
assurance.
 Software testing for an application makes sure that it is
defect-free, saving the cost.
 It helps deliver a high-quality product for a better end-
user experience
 Selecting the right web development framework is
essential to building a high-quality app.
 Jest and react-testing-library are popular framework to
test react apps
Types of test
 Unit test
 In this kind of test, the goal is to verify that each unit of our application, considered in isolation, is
working correctly. An example would be testing that a particular function returns an expected value, give
some known inputs. We’ll see several examples in this article.
 Smoke test
 This kind of test is done to check that the system is up and running. For example, in a React app, we
could just render our main app component and call it a day. If it renders correctly we can be fairly certain
that our app would render on the browser.
 Integration test
 This sort of test is carried out to verify that two or more modules can work well together. For example,
you might run a test to verify that your server and database are actually communicating correctly.
 Functional test
 A functional test exists to verify that the system meets its functional specification.
 End-to-end test
 This kind of test involves testing the application the same way it would be used in the real world.
 Acceptance test
 This is usually done by the business owner to verify that the system meets specifications.
 Performance test
 This sort of testing is carried out to see how the system performs under significant load. In frontend
development, this is usually about how fast the app loads on the browser.
Test example (Continue Counter example)
 Install package
 npm install --save-dev @testing-library/react
 Create a simplified Counter2.js
 import React, { useState } from 'react';

 function Counter2() {
 const [count, setCount] = useState(0);

 function increment() {
 setCount(count + 1);
 }

 return (
 <div>
 <h1 data-testid="counter">{count}</h1>
 <button data-testid="button" onClick={increment}>Increment</button>
 </div>
 );
 }

 export default Counter2;


Add test case file
 Create Counter.test.js and write test
 import React from 'react';
 import { render, fireEvent } from '@testing-library/react';
 import Counter from './Counter';

 test('increments counter', () => {


 const { getByTestId } = render(<Counter2 />);
 const counterElement = getByTestId('counter');
 const buttonElement = getByTestId('button');

 expect(counterElement.textContent).toBe('0');

 fireEvent.click(buttonElement);

 expect(counterElement.textContent).toBe('1');
 });
 Run tests:
 npm test
Test output
 We can notice error in App component, because we
modified App component entirely.

 Delete App.test.js
 Run “npm test” again
DevTools
 Developer tools
 A very useful tool, if you are working on React.js
applications
 It helps you to inspect and edit the React component
tree that builds the page, and for each component, one
can check the props, the state, hooks, etc.
 This tool also helps you to know if a particular
application React.js has been used or not.
 It’s available for chrome and firefox
Download and use DevTools
 Add chrome extension from:
https://chrome.google.com/webstore/detail/react-
developer-
tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en
 Re launch chrome
 Right click and select inspect
 You will see “Components” and “Profile” 2 options
 Show demo
CREATE UI for CRUD operations

You might also like