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

React

React JS

Uploaded by

N. VETHAVALLI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

React

React JS

Uploaded by

N. VETHAVALLI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

SEMESTER:

II 23PCSCS26: OBJECT ORIENTED PROGRAMMING CREDIT:2


PART: A THROUGH JAVA, HTML BASICS HOURS:4
SEC: 1

Course Objectives:
The main objectives of this course are to:
1. To implement the static web pages using HTML and do client side validation using JavaScript.
2. To introduce Node JS implementation for server side programming.
3. To experiment with single page application development using React.

Expected Course Outcomes:


On the successful completion of the course, student will be able to:
1 Develop a proper understanding of Web Development Architecture. K1, K2
2 Create application using React components. K2, K3
3 Perform Navigation using Routes. K3, K4
4 Build Web Applications using React with Redux. K5, K6
5 Perform ReactJS animations K6
K1-Remember; K2-Understand; K3-Apply; K4-Analyze; K5-Evaluate; K6-Create
Unit:1 15hours
ReactJS introduction, why to learn ReactJS, React Environment Setup- pre-requisite for ReactJS, ways to
install ReactJS, ReactJS - Architecture, ReactJS - creating a React Application, React create-react-app,
Features of ReactJS, ReactJS vs Native React, ReactJS
vs AngularJS.

Unit:2 15hours
ReactJS - JSX, ReactJS - components: creating a React component, creating a class component, creating a
function component, ReactJS - styling, ReactJs - properties (props), React Props Validation.

Unit:3 15hours
ReactJS state management, ReactJS event Management, React Constructor, React component API, React
component Life-cycle, React Forms and user input, controlled Component, Un-Controlled Component,
Form link.
Unit:4 15hours
ReactJS - Http client Programming, React Lists, The map() function, React Keys, React Refs, React
Fragments, React Router, ReactCSS, React Animation, React Date picker, DoM in React.

Unit:5 13hours
React AJAX call - HTTP GET request, HTTP GET Request and Looping through data, React Bootstrap,
React Table, React Hooks, React building and deployment.

Unit:6 Contemporary Issues 2 hours


Expert lectures, online seminars– webinars
Total Lecture hours 75hours

Text Books
st
1 Learning React: Functional web Development with React and Redux 1 Edition by Alex Banks.
2 The Road to React: your journey to master plain yet pragmatic React.js by Robin Wieruch
Reference Books
1 React.js Essentials: A fast-paced guide to designing and building scalable and maintainable web apps
with React.jsArtemijFedosejev.
2 Full-Stack React projects: Learn MERN stack development by building modem web apps using
MongoDB, Express, React, and Node.js, 2nd Edition paperback by shamaHoque
3 React.js Book: Learning React Javascript Library From Scratch by Greg Sidelnikov

Related Online Contents [MOOC, SWAYAM, NPTEL, Websites etc.]


1 https://www.mygreatlearning.com/academy/learn-for-free/courses/react-js-tutorial
2 https://www.classcentral.com/course/edx-introduction-to-reactjs-8770

MappingwithProgrammingOutcomes
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10
CO1 S M S M S L M L S M
CO2 S S S S S M S M S M
CO3 S S S S S M S M S M
CO4 S S S S S M S M S M
CO5 S S S S S M S M S M
*S-Strong;M-Medium;L-Low

Unit:1 15hours
ReactJS introduction, why to learn ReactJS, React Environment Setup- pre-requisite for ReactJS, ways to
install ReactJS, ReactJS - Architecture, ReactJS - creating a React Application, React create-react-app,
Features of ReactJS, ReactJS vs Native React, ReactJS
vs AngularJS.
What is React?

React, sometimes referred to as a frontend JavaScript framework, is a JavaScript


library created by Facebook.

React is a tool for building UI components.

React.JS History

Current version of React.JS is V18.0.0 (April 2022).

Initial Release to the Public (V0.3.0) was in July 2013.

React.JS was first used in 2011 for Facebook's Newsfeed feature.

Facebook Software Engineer, Jordan Walke, created it.

Current version of create-react-app is v5.0.1 (April 2022).

create-react-app includes built tools such as webpack, Babel, and ESLint.

why to learn ReactJS

1. The era of Reusable Components:

The very basic and the most important thing you need to know about React
is the Component. React is nothing but one large pile of big components which
call other small components.

While handling big applications using React, we use encapsulation. An application


written in React is basically a composition of smaller React components holding some
state that can be reused anywhere multiple times.

2. Patterns of React

The basic declarative approach is focused on WHAT needs to be done, instead of the
instructions on how it must be done.

Declarative code is useful for making the code more predictable and easier to debug.
With React-based projects, you don’t tell React how to organize the state, you just tell
React ‘I need that state’ and you can rely on React for getting and setting up the state
data. Also, at a higher level, with the help of React, we can achieve global state
management which is typically using some common data logic in the entire system, such
as:

1. User profile data, or

2. Theme Data, or

3. User Journey Data


With React we can create interactive UIs with a declarative approach and also design
simple views for each and every state in our application.

You can rely on React for efficiently updating and rendering the right components when
the data changes.

Before ReactJS entered the stage, it was very difficult to create dynamic web
applications. ReactJS has simplified this process with the help of a JavaScript Extension
known as JSX. It makes machine-readable codes easier.

And it’s very cool and easy to scale the React application.

3. Backward compatibility

Whenever a new version is updated in React, it only increases the ease of use for us and
the public APIs remain the same. This means we need not worry about updating our
application with any new releases of React as the base APIs remain constant.

This means that you do not have to learn a new version after every update. The old
version remains the same, constant, and compatible with the newly added components.

In a practical context, React 16 maintains the exact same public API as in the (15.x and
earlier) previous versions.

4. Concurrent Mode

What is Concurrent mode?

All of us would have definitely experienced this.

Whenever we use an autocomplete form there is a freeze of the cursor at times, mostly
seen in React applications because of its rendering behavior. For example, take a look at
the below diagram. When we try to type “WAIT”, with every key event triggered, UI
gets blocked on updating it
5. SEO Friendly Framework

Most of our applications require ranking to mark their


presence, and Google achieves this ranking with the use
of bots. SEO is a technique to boost user traffic where
all the crawling and indexing is done by these Bots.

Search Engines hate heavy JavaScript pages because of reading troubles when the page
is loaded in the browser. Also, if the basic HTML page contains nothing but some meta
tags and script tags, the search engine will assume that our page is blank and the result is
you get a poor ranking.

React has a pre-rendering feature that helps in getting an SEO friendly platform in both
SPAs or multiple page applications.

Also, in React we can achieve server-side rendering very easily in contrast to the older
JavaScript-based applications where we have to make use of external third-party
libraries. Since JS pages are heavy, crawlers take more time to crawl a page, whereas in
React, a page comes as a single web page with the help of Virtual DOM.

Outlined above are just some of the basic React features. There are still tonnes of
advantages of React, covered in the following pointers:

 Easy to use and easy to learn


 Performance and reusability
 Less Development time
 An amazing Ecosystem, dev tools, and new frameworks
 Single codebase, multiple views
 Ability to build MVP features in a scalable and faster manner
 Component oriented approach
 Performance and reusability

ReactJS Environment Setup

To run any React application, we need to first setup a ReactJS Development


Environment.

pre-requisite for ReactJS,


We must have NodeJS installed on our PC. So, the very first step will be to install
NodeJS. Once we have set up NodeJS on our PC, the next thing we need to do is set up
React Boilerplate

ways to install ReactJS,

There are basically two methods for React JS Environment Setup

 Using create-react-app (faster method)


 Using webpack and babel

Setting up the Node Development Environment


The Node can be installed in multiple ways on a computer. The approach used by you
depends on the existing development environment in the system. There are different
package installer for different environments. You can install Node by grabbing a copy of
the source code and compiling the application. Another way of installing Node is by
cloning the GIT repository in all the three environments and then installing it on the
system.
Installing Node On Windows (WINDOWS 10):
You have to follow the following steps to install the Node.js on your Windows :
Step-1: Downloading the Node.js ‘.msi’ installer.
The first step to install Node.js on windows is to download the installer. Visit the
official Node.js website i.e) https://nodejs.org/en/download/ and download the .msi file
according to your system environment (32-bit & 64-bit). An MSI installer will be
downloaded on your system.
Step-2: Running the Node.js installer.
Now you need to install the node.js installer on your PC. You need to follow the
following steps for the Node.js to be installed:-
 Double click on the .msi installer.
The Node.js Setup wizard will open.

 Welcome To Node.js Setup Wizard.


Select “Next”

 After clicking “Next”, End-User License Agreement (EULA) will open.


Check “I accept the terms in the License Agreement”

Select “Next”
 Destination Folder
Set the Destination Folder where you want to install Node.js & Select “Next”

 Custom Setup
Select “Next”
 Ready to Install Node.js.
The installer may prompt you to “install tools for native modules”
Select “Install”

 Installing Node.js.
Do not close or cancel the installer until the install is complete
 Complete the Node.js Setup Wizard.
Click “Finish”

Step 3: Verify that Node.js was properly installed or not.


To check that node.js was completely installed on your system or not, you can run the
following command in your command prompt or Windows Powershell and test it:-
C:\Users\Admin> node -v

If node.js was completely installed on your system, the command prompt will print the
version of the node.js installed.
If you get a message back saying node was not found, then add it to the path manually:
Adding to the path:
You should not need to do anything to the system variables, as the windows installer
takes care of the system variables itself while installing through the .msi installer.

If you use any other format for installing node.js on your PC, you should put the system
variable path for node.js as follows:
PATH : C:\Users\{username}\AppData\Roaming\npm C:\Program Files\{path to the
nodejs folder}
for example:
PATH : C:\Users\admin\AppData\Roaming\npm C:\Program Files\nodejs
Note: After adding to the PATH, restart the command line, because PATH is only
loaded when initializing new command line sessions.
Step 4: Updating the Local npm version
The final step in node.js installed is the updation of your local npm version(if required)
– the package manager that comes bundled with Node.js.
You can run the following command, to quickly update the npm
npm install npm –global // Updates the ‘CLI’ client

ReactJS – Architecture

React library is built on a solid foundation. It is simple, flexible and extensible.

React elements
JavaScript representation of HTML DOM. React provides an
API, React.createElement to create React Element.

JSX

A JavaScript extension to design user interface. JSX is an XML based, extensible


language supporting HTML syntax with little modification. JSX can be compiled to React
Elements and used to create user interface.

React component
React component is the primary building block of the React application. It uses React
elements and JSX to design its user interface. React component is basically a JavaScript
class (extends the React.component class) or pure JavaScript function. React component
has properties, state management, life cycle and event handler. React component can be
able to do simple as well as advanced logic.

Architecture of the React Application

eact library is just UI library and it does not enforce any particular pattern to write a
complex application. Developers are free to choose the design pattern of their choice.
React community advocates certain design pattern. One of the patterns is Flux pattern.
React library also provides lot of concepts like Higher Order component, Context, Render
props, Refs etc., to write better code. React Hooks is evolving concept to do state
management in big projects. Let us try to understand the high level architecture of a React
application.

 React app starts with a


single root component.
 Root component is build using one or more component.
 Each component can be nested with other component to any level.
 Composition is one of the core concepts of React library. So, each component is
build by composing smaller components instead of inheriting one component
from another component.
 Most of the components are user interface components.
 React app can include third party component for specific purpose such as routing,
animation, state management, etc.

Example
Next, create a file, hello.html and write a simple React application.

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>React Application</title>

</head>
<body>

<div id="react-app"></div>

<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>

<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>

<script language="JavaScript">

element = React.createElement('h1', {}, 'Hello React!')

ReactDOM.render(element, document.getElementById('react-app'));

</script>

</body>

</html>Next, serve the application using serve web server.

serve ./hello.html

Output
Next, open your favorite browser. Enter http://localhost:5000 in the address bar and then
press enter.

Here, we are using two API provided by the React library.

React.createElement

Used to create React elements. It expects three parameters −

 Element tag
 Element attributes as object
 Element content - It can contain nested React element as well

ReactDOM.render

Used to render the element into the container. It expects two parameters −
 React Element OR JSX
 Root element of the webpage

Nested React element


As React.createElement allows nested React element, let us add nested element as shown
below −

Example

<script language="JavaScript">

element = React.createElement('div', {}, React.createElement('h1', {}, 'Hello React!'));

ReactDOM.render(element, document.getElementById('react-app'));
</script>

Output

It will generate the below content −

<div><h1> Hello React!</h1></div>

Use JSX

Next, let us remove the React element entirely and introduce JSX syntax as shown below

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>React Application</title>

</head>

<body>

<div id="react-app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>

<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<script type="text/babel">

ReactDOM.render(

<div><h1>Hello React!</h1></div>,

document.getElementById('react-app')

);

</script>

</body>

</html>

Here, we have included babel to convert JSX into JavaScript and added type="text/babel"
in the script tag.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<script type="text/babel">

...

...

</script>

Next, run the application and open the browser. The output of the application is as follows

By analyzing the application, we can visualize the workflow of the React application as
shown in the below diagram.

Features of ReactJS
Currently, ReactJS gaining quick popularity as the best JavaScript framework among web
developers. It is playing an essential role in the front-end ecosystem. The important
features of ReactJS are as following

o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance

o JSX

JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or
HTML like syntax used by ReactJS. This syntax is processed into JavaScript calls
of React Framework. It extends the ES6 so that HTML like text can co-exist with
JavaScript react code. It is not necessary to use JSX, but it is recommended to use
in ReactJS.

o Components

ReactJS is all about components. ReactJS application is made up of multiple


components, and each component has its own logic and controls. These
components can be reusable which help you to maintain the code when working
on larger scale projects.

o One-way Data Binding

ReactJS is designed in such a manner that follows unidirectional data flow or one-
way data binding. The benefits of one-way data binding give you better control
throughout the application. If the data flow is in another direction, then it requires
additional features. It is because components are supposed to be immutable and
the data within them cannot be changed. Flux is a pattern that helps to keep your
data unidirectional. This makes the application more flexible that leads to increase
efficiency

Virtual DOM

A virtual DOM object is a representation of the original DOM object. It works like a one-
way data binding. Whenever any modifications happen in the web application, the entire
UI is re-rendered in virtual DOM representation. Then it checks the difference between
the previous DOM representation and new DOM. Once it has done, the real DOM will
update only the things that have actually changed. This makes the application faster, and
there is no wastage of memory.
Simplicity

ReactJS uses JSX file which makes the application simple and to code as well as
understand. We know that ReactJS is a component-based approach which makes the code
reusable as your need. This makes it simple to use and learn.

Performance

ReactJS is known to be a great performer. This feature makes it much better than other
frameworks out there today. The reason behind this is that it manages a virtual DOM. The
DOM is a cross-platform and programming API which deals with HTML, XML or
XHTML. The DOM exists entirely in memory. Due to this, when we create a component,
we did not write directly to the DOM. Instead, we are writing virtual components that will
turn into the DOM leading to smoother and faster performance

Difference Between ReactJS and React Native

Comparison
React.js React Native
Factor

React Native is a
command-line
ReactJS is a
interface tool that
Installation JavaScript library
requires both Node.js
Process installed via the npm
and the React Native
package manager.
CLI to be installed.

React Native is more


ReactJs is more
efficient in terms of
efficient in terms of
Efficiency performance and
development time and
memory usage.
code reusability.

Technology ReactJS is a React Native is a


Base JavaScript library cross-platform mobile
used for building user development
interfaces. It uses structure or
a Virtual framework that uses
DOM algorithm to components that are
enhance performance. native instead of web
components as its
building blocks. This
makes it possible to
create apps that have
a more native feel and
look.

React Native is the


ReactJS is the more
more feasible option
feasible option for
Feasibility for mobile app
web application
development.
development.

React Native
ReactJS components components are
are typically written written in JSX, a
in HTML. These syntax extension of
Components components must be JavaScript. These
imported into the app components are
before they can be compiled directly into
used. native code.

React Native is a
framework used for
developing native
It is compatible with a
mobile apps. It is only
Compatibilit vast range of
compatible with the
y browsers, including
two major mobile
Internet Explorer.
platforms, iOS, and
Android.

React Native is a
better choice for
creating native mobile
ReactJS uses a applications than
Navigation traditional browser- ReactJS. React Native
based approach. relies on native
platform navigational
components.

ReactJS is a good
React Native is a
choice for projects
better choice for
that require high-
Storage projects that need to
performance storage,
be able to scale easily.
such as dynamic web
applications.

Search ReactJS is more React Native cannot


Engine search engine friendly be made search
engine friendly - it is
more difficult to
Friendly than React Native. achieve good SEO
with this framework.

React Native is a
React is a framework complete platform
for building that allows building
Platform
applications using native and cross-
JavaScript platform mobile apps

React.js is the most


React Native contains
used JavaScript
all the components of
Learning library for creating
React; So, learning
Curve high-performance
one is useful for both
UIs, which makes it
easy to learn

React Native uses


Browser code in React native APIs to render
Rendering is rendered through all components on
the Virtual DOM mobile

React makes use of React Native uses the


Syntax HTML and its syntax React Native syntax
flow

React Native uses the


React works well with
Support for Animated API to
CSS for styling and
CSS animate the c
animations

AngularJS ReactJS

Author Google Facebook Community


Developer Misko Hevery Jordan Walke
Initial Release October 2010 March 2013
Latest Angular 1.7.8 on 11 March React 16.8.6 on 27 March
Version 2019. 2019
Language JavaScript, HTML JSX
Type Open Source MVC Open Source JS
Framework Framework
Rendering Client-Side Server-Side
Packaging Weak Strong
Data-Binding Bi-directional Uni-directional
DOM Regular DOM Virtual DOM
Testing Unit and Integration Testing Unit Testing
App MVC Flux
Architecture
Dependencies It manages dependencies It requires additional tools
automatically. to manage dependencies.
Routing It requires a template or It doesn't handle routing
controller to its router but has a lot of modules
configuration, which has to be for routing, eg., react-
managed manually. router.
Performance Slow Fast, due to virtual DOM.
Best For It is best for single page It is best for single page
applications that update a applications that update
single view at a time. multiple views at a time.

Unit:2
ReactJS - JSX, ReactJS - components: creating a React component, creating a class component, creating a
function component, ReactJS - styling, ReactJs - properties (props), React Props Validation.
What is React JSX ?
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript. It
helps us to write HTML in JavaScript and forms the basis of React Development. Using
JSX is not compulsory but it is highly recommended for programming in React as it
makes the development process easier as the code becomes easy to write and read.
JSX creates an element in React that gets rendered in the UI. It is transformed into
JavaScript functions by the compiler at runtime. Error handling and warnings become
easier to handle when using JSX

Sample JSX code:


const ele = <h1>This is sample JSX</h1>;
The above code snippet somewhat looks like HTML and it also uses a JavaScript-like
variable but is neither HTML nor JavaScript, it is JSX(JavaScript XML). With the help
of JSX, we have directly written the HTML syntax in JavaScript
Why JSX ?
 It is faster than normal JavaScript as it performs optimizations while translating to
regular JavaScript.
 It makes it easier for us to create templates.
 Instead of separating the markup and logic in separate files, React
uses components for this purpose. We will learn about components in detail in further
articles.
 As JSX is an expression, we can use it inside of if statements and for loops, assign it
to variables, accept it as arguments, or return it from functions.
Expressions in JSX
In React we are allowed to use normal JavaScript expressions with JSX. To embed any
JavaScript expression in a piece of code written in JSX we will have to wrap that
expression in curly braces {}. The below example specifies a basic use of JavaScript
Expression in React.
Syntax:
const example = "JSX"
const ele = <div>This component uses {example} </div>

Example: This example wraps the JSX code in curly braces


javascript

// Filename - App.js

import React from "react";

const name = "Learner";

const element = (

<h1>

Hello,

{name}.Welcome to GeeksforGeeks.
</h1>

);

ReactDOM.render(element, document.getElementById("root"));

Output:

Wrapping elements or Children in JSX


Consider a situation where you want to render multiple tags at a time. To do this we
need to wrap all of these tags under a parent tag and then render this parent element to
the HTML. All the subtags are called child tags or children of this parent element.
Example: In this example we have wrapped h1, h2, and h3 tags under a single div
element and rendered them to HTML:
Javascript

// Filename - App.js

import React from "react";

import ReactDOM from "react-dom";

const element = (

<div>

<h1>This is Heading 1 </h1>

<h2>This is Heading 2</h2>

<h3>This is Heading 3 </h3>

</div>

);
ReactDOM.render(element, document.getElementById("root"));

Output:

What are React JS Components ?


A Component is one of the core building blocks of React. In other words, we can say
that 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.

Types of Components in React JS :

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, we will discuss this later in the tutorial. The below example
shows a valid functional component in React:

Syntax for Funtional Components:

function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}

Example

Create a constructor function in the Car component, and add a color property:

class Car extends React.Component {

constructor() {

super();
this.state = {color: "red"};

render() {

return <h2>I am a Car!</h2>;

Class Components:
The class components are a 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 another class component. We can use JavaScript ES6 classes to create
class-based components in React. The below example shows a valid class-based
component in React:

Syntax for Class Components:

class Democomponent extends React.Component {


render() {
return <h1>Welcome Message!</h1>;
}
}

Example

Create a Class component called Car

class Car extends React.Component {

render() {

return <h2>Hi, I am a Car!</h2>;

Now your React application has a component called Car, which returns a <h2> element.

To use this component in your application, use similar syntax as normal HTML: <Car />
Example

Display the Car component in the "root" element:

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

root.render(<Car />);

ReactJS - styling, ReactJs - properties (props),

There are many ways to style React with CSS, this tutorial will take a
closer look at inline styling, and CSS stylesheet.

Inline Styling

To style an element with the inline style attribute, the value must be a JavaScript object:

class MyHeader extends React.Component {

render() {

return (

<div>

<h1 style={{color: "red"}}>Hello Style!</h1>

<p>Add a little style!</p>

</div>

);

}
camelCased Property Names

Since the inline CSS is written in a JavaScript object, properties with two names,
like background-color, must be written with camel case syntax:

Use backgroundColor instead of background-color

class MyHeader extends React.Component {

render() {

return (

<div>

<h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>

<p>Add a little style!</p>

</div>

);

}
JavaScript Object

You can also create an object with styling information, and refer to it in the style attribute

Create a style object named mystyle:

class MyHeader extends React.Component {

render() {

const mystyle = {

color: "white",

backgroundColor: "DodgerBlue",

padding: "10px",

fontFamily: "Arial"

};

return (

<div>

<h1 style={mystyle}>Hello Style!</h1>

<p>Add a little style!</p>


</div>

);

mystyle.module.css:

Create a new file called "mystyle.module.css" and insert some CSS code in it:

.bigblue {

color: DodgerBlue;

padding: 40px;

font-family: Arial;

text-align: center;

}
Import the stylesheet in your component:

App.js:

import React from 'react';

import ReactDOM from 'react-dom/client';

import styles from './mystyle.module.css';

class Car extends React.Component {

render() {

return <h1 className={styles.bigblue}>Hello Car!</h1>;

export default Car;

Import the component in your application:

index.js:

import React from 'react';

import ReactDOM from 'react-dom/client';

import Car from './App.js';

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


React Props Validation

Props are an important mechanism for passing the read-only attributes to React
components. The props are usually required to use correctly in the component. If it is not
used correctly, the components may not behave as expected. Hence, it is required to
use props validation in improving react components.

Props validation is a tool that will help the developers to avoid future bugs and problems.
It is a useful way to force the correct usage of your components. It makes your code more
readable. React components used special property PropTypes that help you to catch bugs
by validating data types of values passed through props, although it is not necessary to
define components with propTypes. However, if you use propTypes with your
components, it helps you to avoid unexpected bugs.

Validating Props

App.propTypes is used for props validation in react component. When some of the props
are passed with an invalid type, you will get the warnings on JavaScript console. After
specifying the validation patterns, you will set the App.defaultProps.

Syntax:
1. class App extends React.Component {
2. render() {}
3. }
4. Component.propTypes = { /*Definition */};
ReactJS Props Validator

ReactJS props validator contains the following list of validators

S PropsType Descriptio
N n

1. PropTypes.any The props


can be of
any data
type.
2. PropTypes.array The props
should be
an array.
3. PropTypes.bool The props
should be a
boolean.
4. PropTypes.func The props
should be a
function.
5. PropTypes.number The props
should be a
number.
6. PropTypes.object The props
should be
an object.
7. PropTypes.string The props
should be a
string.
8. PropTypes.symbol The props
should be a
symbol.
9. PropTypes.instanceOf The props
should be
an instance
of a
particular
JavaScript
class.
10. PropTypes.isRequired The props
must be
provided.
11. PropTypes.element The props
must be an
element.
12. PropTypes.node The props
can render
anything:
numbers,
strings,
elements or
an array (or
fragment)
containing
these types.
13. PropTypes.oneOf() The props
should be
one of
several
types of
specific
values.
14. PropTypes.oneOfType([PropTypes.string,PropTypes.nu The props
mber]) should be
an object
that could
be one of
many
types.

Unit:3

ReactJS state management, ReactJS event Management, React Constructor, React component API, React
component Life-cycle, React Forms and user input, controlled Component, Un-Controlled Component,
Form link.

What is React State Management?


React components have a built-in state object. The state is encapsulated
data where you store assets that are persistent between component
renderings.

The state is just a fancy term for a JavaScript data structure. If a user
changes state by interacting with your application, the UI may look
completely different afterwards, because it's represented by this new state
rather than the old state.

React applications are built using components and they manage their state
internally and it works well for applications with few components, but when
the application grows bigger, the complexity of managing states shared
across components becomes difficult.

Here is a simple example of an e-commerce application, in which the


status of multiple components will change when purchasing a product.

 Add that product to the shopping list


 Add product to customer history
 trigger count of purchased products

If developers do not have scalability in mind then it is really hard to find out
what is happening when something goes wrong. This is why you need
state management in your application.

What is React State Management?

React components have a built-in state object. The state is


encapsulated data where you store assets that are persistent between
component renderings. The state is just a fancy term for a JavaScript
data structure.

Application state management is the process of maintaining knowledge of an application's inputs across

multiple related data flows that form a complete business transaction -- or a session -- to understand the

condition of the app at any given moment. In computer science, an input is information put into the program

by the user and state refers to the condition of an application according to its stored inputs -- saved as variables

or constants.

Core business applications process sensitive information like orders, payments, invoices and bills of material.

This processing depends on the state of the application and results in changes to the balance of inventories,
accounts and financial ledgers. State management allows developers to determine the state of the application

to ensure the changes made appropriately reflect the real-world context and business processes.

There are two accepted models for state management: Front end (also called client side), and back end

(sometimes called server side).

In front-end state management, the user's own app or browser maintains the program's state, often by having

certain buttons or UI features enabled or disabled and sending the state along with the message. The user

interface connection ensures the user and the application are in harmony throughout the session.

In back-end state management, an application component will use an external data structure or database to

record the final state when it's done processing activities. Processing the next message will start with retrieving

the previous state from the database. The state variable in the data structure can also synchronize the user

interface -- and through it the user -- with the state of the session.

State management in application development

Early applications controlled the user dialog, so the individual steps within a session were dictated by the

process itself; write data to the user, accept changes, confirm them and commit them. With the advent of web

applications based on the stateless vision of HTML, it became necessary to more clearly define state

management practices.

When a session message -- such as an HTML page -- is received, it is interpreted based on the state, which is

recorded as a variable or constant that every process can access. The record ensures that receiving, for

example, a "confirmation" message while in the "waiting for confirmation" state is handled differently than it

would be in the "waited too long for user response state." That, in turn, ensures that application systems that

update databases and produce durable business records are always synchronized with the real world.

Advantages of state management

State management is essential in aligning and integrating core business applications and the cloud. Without

some form of state management, business activities as routine as the purchase of something or a request for
information would have to be structured as a single request or response exchange. This could put a significant

burden on the user and would almost certainly reduce the effectiveness of the application. In some cases, such

as the processing of an order, a stateless exchange could hide critical information like current stock levels,

resulting in what could be a significant business impact on the seller and a major inconvenience to the buyer.

Tools

State management tools are typically offered in the form of state management libraries, designed for

developers who want to build state awareness into their applications. Most of these tools are used to

implement front-end state management because that mechanism is easiest to execute and offers the tightest

integration with the application's user base. Front-end state control is also ideal for state management when the

goal of development is to add a cloud front end to a business process.

Most tools work by adding a state object to something like JavaScript. This object and its methods are then

used to manage state and prevent loss of state under unusual conditions, including contamination by code or

changes in client-server relationships. Libraries like React focus almost entirely on the user interface. Other

libraries, like Redux or Cerebral, provide an integrated form of state management used throughout the

workflow. Flutter is an SDK that can be used a bit more broadly, in both front-end and back-end state

management applications.

ReactJS - Event Management

Events are just some actions performed by a user to


interact with any application. They can be the smallest of
actions, like hovering a mouse pointer on an element that
triggers a drop-down menu, resizing an application
window, or dragging and dropping elements to upload
them etc. Events in React are divided into three
categories:

 Mouse Events − onClick, onDrag, onDoubleClick


 Keyboard Events − onKeyDown, onKeyPress,
onKeyUp
 Focus Events − onFocus, onBlur

For each of these events, JavaScript provides


responses. So, every time an event is
performed by the user, it usually requires
some type of reaction from the application;
and these reactions are defined as some
functions or blocks of code, called Event
Handlers. This entire process of working with
events using Event Handlers is known
as Event Management
Event Management in ReactJS

Event management is one of the important features in a web application.


It enables the user to interact with the application. React supports all
events available in a web application. React event handling is very
similar to DOM events with little changes. Following are some of the
common events one can observe in React-based websites −

Clicking on a component.

Scrolling the current page.

Hovering over elements of the current page.

Submitting a form.

Redirecting to another webpage.

Loading images.
Synthetic React Events

In JavaScript, when an event is specified, you will be dealing with a


react event type called a synthetic event instead of regular DOM events.
SyntheticEvent is a simple cross-browser wrapper for native event
instances making the events work identically across all browsers. All
event handlers must be passed as instances of this wrapper. However, it
is expensive in terms of CPU resources as every synthetic event created
needs to be garbage-collected. Every synthetic event object has the
following attributes:

boolean bubbles

boolean cancelable

DOMEventTarget currentTarget

boolean defaultPrevented

number eventPhase

boolean isTrusted

DOMEvent nativeEvent

void preventDefault()

boolean isDefaultPrevented()
void stopPropagation()

boolean isPropagationStopped()

void persist()

DOMEventTarget target

number timeStamp

string type

Since synthetic events use a lot of resources, they are usually reused and
all its properties will be nullified after invoking the event callback to
optimize their performance in the browser. SyntheticEvent has the same
interface as the native event. And as the synthetic events are authorized
by the document node, native events are triggered first followed by the
synthetic events.

Adding an Event

As we have already seen, React has the same events as HTML: click,
change, mouseover etc. However, the React events are defined with a
camelCase and the reaction is written inside the curly braces instead.
The syntax of adding an event differs in a functional component and
class component.

Following is the syntax to add an onClick event in a functional


component of React:

onClick = {action to be performed}


Following is the syntax to add an onClick event in a class component of
React:

onClick = {this.action_to_be_performed}

Handling an Event

Let us now learn how to handle these events in a React application with
the help of the following step-by-step process.

Define an event handler method to handle the given event.

log() {

console.log("Event is fired");

React provides an alternative syntax using lambda function to define


event handler. The lambda syntax is −

log = () => {

console.log("Event is fired");

Passing Arguments to Event Handler

There are two methods available to pass arguments to an Event Handler:

Arrow Method

Bind Method

Arrow Method
If you want to know the target of the event, then add an argument e in
the handler method. React will send the event target details to the
handler method.

log(e) {

console.log("Event is fired");

console.log(e.target);

The alternative lambda syntax is −

log = (e) => {

console.log("Event is fired");

console.log(e.target);

If you want to send extra details during an event, then add the extra
details as initial argument and then add argument (e) for event target.

log(extra, e) {

console.log("Event is fired");

console.log(e.target);

console.log(extra);

console.log(this);

The alternative lambda syntax is as follows −

log = (extra, e) => {

console.log("Event is fired");
console.log(e.target);

console.log(extra);

console.log(this);

Bind Method

We can also bind the event handler method in the constructor of the
component. This will ensure the availability of this in the event handler
method.

constructor(props) {

super(props);

this.logContent = this.logContent.bind(this);

If the event handler is defined in alternate lambda syntax, then the


binding is not needed. this keyword will be automatically bound to the
event handler method.

Set the event handler method for the specific event as specified below −

<div onClick={this.log}> ... </div>

To set extra arguments, bind the event handler method and then pass the
extra information as second argument.

<div onClick={this.log.bind(this, extra)}> ... </div>

The alternate lambda syntax is as follows −

<div onClick={this.log(extra, e)}> ... </div>


React.js constructor() Method

A constructor is a method that is called automatically when we created an object from that class. It can manage initial
initialization tasks such as defaulting certain object properties or sanity testing the arguments passed in. Simply
placed, the constructor is a method that helps in the creation of objects.
The constructor is no different in React. This can connect event handlers to the component and/or initialize the
component’s local state. Before the component is mounted, the constructor() function is shot, and, like most things in
React, it has a few rules that you can follow when using them.
 Step 1: Call super(props) before using this.props
Due to the nature of the constructor, this.props object is not accessible straight out of the gate,
which can lead to errors. An error will be thrown by this constructor:

constructor() {

console.log(this.props);

Instead, we transfer the value of a prop to the super() function from the
constructor():

constructor(props) {

super(props);

console.log(this.props);

When you call the super() function, the parent class constructor is
called, which is in the case of a React is React.Component.

Step 2: Never call setState() inside constructor()

The constructor of your component is the ideal place to set the


component’s initial state. You must set the initial state directly, rather
than using setState() as you can in other methods in your class:

constructor(props) {

super(props);
this.state = {

name 'kapil',

age: 22,

};

The only place you can assign the local state directly like that is the
constructor. You should depend on setState() somewhere else inside our
component instead.

Step 3: Avoid assigning values from this.props to this.state

You should try to avoid setting values from the properties when setting
the initial component state in the constructor. We can do the following:

constructor(props) {

super(props);

this.state = {

name: props.name,

};

You wouldn’t be allowed to use setState() to change the property later.


You may easily reference the property directly in your code by naming
this.props.name, instead of assigning the property directly to the state.

Step 4: Bind events all in one place


We can easily bind your event handlers in the constructor:

constructor(props) {

super(props);

this.state = {

// Sets that initial state

};

// Our event handlers

this.onClick = this.onClick.bind(this);

this.onKeyUp = this.onKeyUp.bind(this);

// Rest Code

Creating React Application:

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it


using the following command.

cd foldername

Project Structure: It will look like the following.


Example: Now write down the following code in the App.js file. Here,
App is our default component where we have written our code. The
following example covers constructor demonstration.

App.js

import React, { Component } from 'react';

class App extends Component {

constructor(props) {

// Calling super class constructor

super(props);

// Creating state

this.state = {

data: 'My name is User'

// Binding event handler

this.handleEvent = this.handleEvent.bind(this);

handleEvent() {

console.log(this.props);

}
render() {

return (

<div >

<input type="text" value={this.state.data} />

<br></br> <br></br>

<button onClick={this.handleEvent}>Please Click</button>

</div>

);

export default App;

Step to Run Application: Run the application from the root directory of
the project, using the following command

npm start

Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate during its three main
phases.

The three phases are: Mounting, Updating, and Unmounting.

Mounting
Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()

The render() method is required and will always be called, the others are optional and will be called if
you define them.

constructor

The constructor() method is called before anything else, when the component is initiated, and it is the
natural place to set up the initial state and other initial values.

The constructor() method is called with the props, as arguments, and you should always start by
calling the super(props) before anything else, this will initiate the parent's constructor method and
allows the component to inherit methods from its parent ( React.Component).

The constructor method is called, by React, every time you make a


component:

class Header extends React.Component {

constructor(props) {

super(props);

this.state = {favoritecolor: "red"};

render() {

return (

<h1>My Favorite Color is {this.state.favoritecolor}</h1>

);

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


getDerivedStateFromProps

The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM.

This is the natural place to set the state object based on the initial props.

It takes state as an argument, and returns an object with changes to the state.

The example below starts with the favorite color being "red", but
the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:

Example:

The getDerivedStateFromProps method is called right before the render method:

class Header extends React.Component {

constructor(props) {

super(props);

this.state = {favoritecolor: "red"};

static getDerivedStateFromProps(props, state) {

return {favoritecolor: props.favcol };

render() {

return (

<h1>My Favorite Color is {this.state.favoritecolor}</h1>

);

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));

Run Example »
render

The render() method is required, and is the method that actually outputs the HTML to the DOM.

Example:

A simple component with a simple render() method:

class Header extends React.Component {

render() {

return (

<h1>This is the content of the Header component</h1>

);

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

Run Example »

componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

Example:
At first my favorite color is red, but give me a second, and it is yellow instead:

class Header extends React.Component {

constructor(props) {

super(props);

this.state = {favoritecolor: "red"};

componentDidMount() {

setTimeout(() => {

this.setState({favoritecolor: "yellow"})
}, 1000)

render() {

return (

<h1>My Favorite Color is {this.state.favoritecolor}</h1>

);

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

Run Example »

Updating
The next phase in the lifecycle is when a component is updated.

React Forms
Adding Forms in React

You add a form with React like any other element:

Example:Get your own React.js Server

Add a form that allows users to enter their name:


function MyForm() {

return (

<form>

<label>Enter your name:

<input type="text" />

</label>

</form>

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

root.render(<MyForm />);

This will work as normal, the form will submit and the page will
refresh.

But this is generally not what we want to happen in React.

We want to prevent this default behavior and let React control the form.

Handling Forms

Handling forms is about how you handle the data when it changes value
or gets submitted.

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.

We can use the useState Hook to keep track of each inputs value and
provide a "single source of truth" for the entire application.

See the React Hooks section for more information on Hooks.

Example:

Use the useState Hook to manage the input:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [name, setName] = useState("");

return (

<form>

<label>Enter your name:

<input

type="text"

value={name}

onChange={(e) => setName(e.target.value)}


/>

</label>

</form>

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

root.render(<MyForm />);

Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute for the <form>:

Example:

Add a submit button and an event handler in the onSubmit attribute:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [name, setName] = useState("");

const handleSubmit = (event) => {

event.preventDefault();

alert(`The name you entered was: ${name}`)

return (

<form onSubmit={handleSubmit}>

<label>Enter your name:

<input
type="text"

value={name}

onChange={(e) => setName(e.target.value)}

/>

</label>

<input type="submit" />

</form>

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

root.render(<MyForm />);

Run Example »

Multiple Input Fields


You can control the values of more than one input field by adding a name attribute to each element.

We will initialize our state with an empty object.

To access the fields in the event handler use


the event.target.name and event.target.value syntax.

To update the state, use square brackets [bracket notation] around the property name.

Example:
Write a form with two input fields:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [inputs, setInputs] = useState({});

const handleChange = (event) => {


const name = event.target.name;

const value = event.target.value;

setInputs(values => ({...values, [name]: value}))

const handleSubmit = (event) => {

event.preventDefault();

alert(inputs);

return (

<form onSubmit={handleSubmit}>

<label>Enter your name:

<input

type="text"

name="username"

value={inputs.username || ""}

onChange={handleChange}

/>

</label>

<label>Enter your age:

<input

type="number"

name="age"

value={inputs.age || ""}

onChange={handleChange}

/>

</label>

<input type="submit" />

</form>

)
}

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

root.render(<MyForm />);

Select
A drop down list, or a select box, in React is also a bit different from HTML.

in HTML, the selected value in the drop down list was defined with the selected attribute:

HTML:
<select>

<option value="Ford">Ford</option>

<option value="Volvo" selected>Volvo</option>

<option value="Fiat">Fiat</option>

</select>

In React, there are two ways of handling form data:

 Controlled Components: In this approach, form data is handled by


React through the use of hooks such as the useState hook.
 Uncontrolled Components: Form data is handled by the Document
Object Model (DOM) rather than by React. The DOM maintains the state
of form data and updates it based on user input.
 This is similar to uncontrolled components in React. You place a form
element in the component, and the DOM takes control of it. The DOM
decides the state of the input element and updates it based on a user's
input.
 In the second approach, you take control of the bike. You hold the
handlebars and pedal, and you decide where to go and how fast to ride.
You can easily slow down or speed up as needed.
 This is similar to controlled components where a React component takes
control of the form data, and maintains the state of form elements. The
component decides when and how to update the state, and it re-renders
itself based on the state changes.

Controlled Components in React


In React, a controlled component is a component where form elements derive
their value from a React state.

When a component is controlled, the value of form elements is stored in a state,


and any changes made to the value are immediately reflected in the state.

To create a controlled component, you need to use the value prop to set the value
of form elements and the onChange event to handle changes made to the value.
The value prop sets the initial value of a form element, while the onChange event is
triggered whenever the value of a form element changes. Inside
the onChange event, you need to update the state with the new value using a state
update function

import {useState} from 'react';

export default function ControlledComponent() {

const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {

setInputValue(event.target.value);

};

return (

<form>
<label>Input Value:
<input type="text" value={inputValue}
onChange={handleChange} />

</label>

<p>Input Value: {inputValue}</p>

</div>

)};
In this example:

The useState hook defines a state variable (inputValue) and a state update
function (setInputValue).
The value prop sets the initial value of the input element to the value
of inputValue.
Also, the onChange event handles changes made to the input value.
The handleChange function updates the inputValue state with the new value of the
input element, and the updated value is immediately reflected in the state

import {useState} from 'react';

export default function ControlledComponent() {

const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {

setInputValue(event.target.value);

};

return (

<form>

<label>Input Value:
<input type="text" value={inputValue}
onChange={handleChange} />

</label>

<p>Input Value: {inputValue}</p>

</div>

)};
In this example:
The useState hook defines a state variable (inputValue) and a state update
function (setInputValue).
The value prop sets the initial value of the input element to the value
of inputValue.
Also, the onChange event handles changes made to the input value.
The handleChange function updates the inputValue state with the new value of the
input element, and the updated value is immediately reflected in the state

Uncontrolled Components in React


Uncontrolled components in React refer to form elements whose state is not
managed by React. Instead, their state is handled by the browser's DOM.

For instance, let's say you have a form that consists of a text input field, a select
box, and a checkbox. In a controlled component, you would create a state for
each form element and write event handlers to update the state whenever the
user interacts with any of the form elements.

In contrast, an uncontrolled component allows the browser to handle the form


elements' state. When a user enters text into a text input field or selects an option
from a select box, the browser updates the DOM's state for that element
automatically.

To get the value of an uncontrolled form element, you can use a feature called
"ref". "Refs" provide a way to access the current value of DOM elements. You can
create a "ref" using the useRef hook, then attach it to the form element you want to
access. This allows you to retrieve the current value of an element at any time,
without needing to manage its state in your React component.
Here's an example of an uncontrolled component:

import { useRef } from "react";

export default function Uncontrolled() {

const selectRef = useRef(null);

const checkboxRef = useRef(null);

const inputRef = useRef(null);

function handleSubmit(event) {

event.preventDefault();
console.log("Input value:", inputRef.current.value);
console.log("Select value:", selectRef.current.value);
console.log("Checkbox value:", checkboxRef.current.checked);
}

return (

<form onSubmit={handleSubmit}>
<label>

<p>Name:</p>

<input ref={inputRef} type="text" />

</label>

<label>

<p>Favorite color:</p>
<select ref={selectRef}>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>

</label>

<label>

Do you like React?


<input type="checkbox" ref={checkboxRef} />

</label>

<button type="submit">Submit</button>
</form>

);

Unit:4

ReactJS - Http client Programming, React Lists, The map() function, React Keys, React Refs, React
Fragments, React Router, ReactCSS, React Animation, React Date picker, DoM in React.

ReactJS - Http Client Programming

Http client programming enables the


application to connect and fetch data from
http server through JavaScript. It reduces the
data transfer between client and server as it
fetches only the required data instead of the
whole design and subsequently improves the
network speed.

Creating the Expense REST API Server

Before we dive into React, let’s set up an Expense REST API server using the
Express framework. This server will serve as our data source.

1. Create a Server Directory:


mkdir apiserver

Initialize a Node.js App:

npm init

Install Dependencies:

npm install express nedb cors

1. Create Initial Data:

2. Generate a CSV file (e.g., data.csv) containing sample expense data.

3. Load Data into a Database:

4. Develop expensedb.js to load initial data into a database (using NeDB).

5. Define Server Routes:

6. Establish routes in server.js for listing, adding, updating, and deleting


expense entries.

7. Start the Server:

npm start

With this setup, you will have a server running at http://localhost:8000/api/expense .

Harnessing the fetch() API in React

Now, let’s build a React application that interacts with our Expense REST API
server using the fetch() API.
1. Create a React Application:

2. Set up a new React app (e.g., react-http-app) and establish the necessary
folder structure.

3. Define CSS Styles:

4. Create a CSS file for styling the expense entry list


(e.g., ExpenseEntryItemList.css).

5. Develop a React Component:

6. Build an ExpenseEntryItemList.js component to list, add, update, and delete


expense entries.

7. Fetching Data:

8. Utilize the fetch() API to retrieve data from the server.

9. Displaying Data:

10. Render the fetched data within your React component.

With this setup, you’ve not only grasped HTTP client programming in React
but also empowered your application to efficiently communicate with the
server.

React Lists
In React, you will render lists with some type of loop.

The JavaScript map() array method is generally the preferred method.

function Car(props) {

return <li>I am a { props.brand }</li>;

}
function Garage() {

const cars = ['Ford', 'BMW', 'Audi'];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car brand={car} />)}

</ul>

</>

);

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

root.render(<Garage />);

Run Example »

Example:
Let's refactor our previous example to include keys:

function Car(props) {

return <li>I am a { props.brand }</li>;

}
function Garage() {

const cars = [

{id: 1, brand: 'Ford'},

{id: 2, brand: 'BMW'},

{id: 3, brand: 'Audi'}

];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car key={car.id} brand={car.brand} />)}

</ul>

</>

);

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

root.render(<Garage />);
React Keys are useful when working with dynamically created
components or when editing a list by the user. Setting the key value
uniquely identifies the component even after modification.

It also helps determine which components in a collection need to be re-


rendered instead of re-rendering the entire set of components each time.

Keys must be specified in the field for elements to have stable IDs. We
recommend choosing the key as a string that uniquely identifies an item
in the list.

Example

const stringLists = [ 'Student1', 'Student2, 'Student3', 'Student4',


'Student5' ];

const updatedLists = stringLists.map((strList)=>{

<li key={strList.id}> {strList} </li>;

});

If there are no stable IDs for rendered items, you can assign the item
index as a key to the lists. It can be shown in the below example.

const stringLists = [ 'Student1', 'Student2, 'Student3', 'Student4',


'Student5' ];

const updatedLists = stringLists.map((strList, index)=>{

<li key={index}> {strList} </li>;

});
Using Keys

Let’s dynamically create a content item with a unique index (i). The
map function creates three elements from the data array. Since the value
of the key must be unique for each element, we also assign it as a key to
each element created.

To avoid mistakes, you have to keep in mind that keys only make sense
in the context of the surrounding array. So, anything you are returning
from the map() function is recommended to be assigned a key.

App.jsx

import React from 'react';

class App extends React.Component {

constructor() {

super();

this.state = {

data:[

component: 'First...',

id: 1

},

component: 'Second...',

id: 2

},
{

component: 'Third...',

id: 3

render() {

return (

<div>

<div>

{this.state.data.map((dynamicComponent, i) => <Content

key = {i} componentData = {dynamicComponent}/>)}

</div>

</div>

);

class Content extends React.Component {

render() {

return (

<div>

<div>{this.props.componentData.component}</div>

<div>{this.props.componentData.id}</div>

</div>

);
}

export default App;

main.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

Output

First….

Second….

Third….

When to Use Refs


There are a few good use cases for refs:

 Managing focus, text selection, or media playback.


 Triggering imperative animations.
 Integrating with third-party DOM libraries.
Avoid using refs for anything that can be done declaratively.
For example, instead of exposing open() and close() methods on a Dialog component, pass
an isOpen prop to it.
Don’t Overuse Refs
Your first inclination may be to use refs to “make things happen” in your app. If this is the
case, take a moment and think more critically about where state should be owned in the
component hierarchy. Often, it becomes clear that the proper place to “own” that state is at
a higher level in the hierarchy. See the Lifting State Up guide for examples of this.

Creating Refs
Refs are created using React.createRef() and attached to React elements via
the ref attribute. Refs are commonly assigned to an instance property when a component is
constructed so they can be referenced throughout the component.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
Accessing Refs
When a ref is passed to an element in render, a reference to the node becomes accessible at
the current attribute of the ref.
const node = this.myRef.current;

The value of the ref differs depending on the type of the node:
 When the ref attribute is used on an HTML element,
the ref created in the constructor
with React.createRef() receives the underlying DOM
element as its current property.
 When the ref attribute is used on a custom class
component, the ref object receives the mounted instance
of the component as its current.
 You may not use the ref attribute on function
components because they don’t have instances.
The examples below demonstrate the differences.
Adding a Ref to a DOM Element
This code uses a ref to store a reference to a DOM node:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef(); this.focusTextInput =
this.focusTextInput.bind(this);
}

focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus(); }

render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} /> <input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
React will assign the current property with the DOM element when the component mounts,
and assign it back to null when it unmounts. ref updates happen
before componentDidMount or componentDidUpdate lifecycle methods.
Adding a Ref to a Class Component
If we wanted to wrap the CustomTextInput above to simulate it being clicked immediately
after mounting, we could use a ref to get access to the custom input and call
its focusTextInput method manually:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }

componentDidMount() {
this.textInput.current.focusTextInput(); }

render() {
return (
<CustomTextInput ref={this.textInput} /> );
}
}
Note that this only works if CustomTextInput is declared as a class:
class CustomTextInput extends React.Component { // ...
}
Refs and Function Components
By default, you may not use the ref attribute on function components because they
don’t have instances:
function MyFunctionComponent() { return <input />;
}

class Parent extends React.Component {


constructor(props) {
super(props);
this.textInput = React.createRef(); }
render() {
// This will *not* work!
return (
<MyFunctionComponent ref={this.textInput} /> );
}
}
If you want to allow people to take a ref to your function component, you can
use forwardRef (possibly in conjunction with useImperativeHandle), or you can convert the
component to a class.
You can, however, use the ref attribute inside a function component as long as you
refer to a DOM element or a class component:
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it const textInput =
useRef(null);
function handleClick() {
textInput.current.focus(); }
return (
<div>
<input
type="text"
ref={textInput} /> <input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}

These new documentation pages teach modern React:


 <Fragment>

A common pattern in React is for a component to return multiple elements. Fragments let
you group a list of children without adding extra nodes to the DOM.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
There is also a new short syntax for declaring them.

Motivation
A common pattern is for a component to return a list of children. Take this example React
snippet:
class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}
<Columns /> would need to return multiple <td> elements in order for the rendered HTML to
be valid. If a parent div was used inside the render() of <Columns />, then the resulting
HTML will be invalid.
class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}
results in a <Table /> output of:
<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>

Fragments solve this problem.

Usage
class Columns extends React.Component {
render() {
return (
<React.Fragment> <td>Hello</td>
<td>World</td>
</React.Fragment> );
}
}
which results in a correct <Table /> output of:
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
Short Syntax
There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:
class Columns extends React.Component {
render() {
return (
<> <td>Hello</td>
<td>World</td>
</> );
}
}
You can use <></> the same way you’d use any other element except that it doesn’t support
keys or attributes.
Keyed Fragments
Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for
this is mapping a collection to an array of fragments — for example, to create a description
list:
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
key is the only attribute that can be passed to Fragment. In the future, we may add support
for additional attributes, such as event handlers.

You might also like