Awesome React

Download as pdf or txt
Download as pdf or txt
You are on page 1of 335

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/372831147

Awesome React.js (Unleash the Power of Modern UI Building)

Book · August 2023

CITATIONS READS

4 4,247

2 authors:

Poornima Naik Kavita Oza


CHHATRAPATI SHAHU INSTITUTE OF BUSINESS EDUCATION AND RESEARCH Shivaji University, Kolhapur
195 PUBLICATIONS 208 CITATIONS 117 PUBLICATIONS 249 CITATIONS

SEE PROFILE SEE PROFILE

All content following this page was uploaded by Poornima Naik on 03 August 2023.

The user has requested enhancement of the downloaded file.


Awesome React.js
(Unleash the Power of Modern UI Building)

By
Dr. Poornima G. Naik
Dr. Kavita S. Oza
Awesome React.js

Awesome React.js
(Unleash the Power of Modern UI
Building)

Author(s): Dr. Poornima G. Naik, Dr. Kavita S. Oza

Vol. 1 July 2023

ISBN: 978-81-961331-4-6

Published By:
Copyright ©International Institute of Organized Research (I2OR), India – 2023
Number 3179, Sector 52, Chandigarh (160036) - India

The responsibility of the contents and the opinions expressed in this book is exclusively of the author(s)
concerned. The publisher/editor of the book is not responsible for errors in the contents or any consequences
arising from the use of information contained in it. The opinions expressed in the book chapters/articles/research
papers in book do not necessarily represent the views of the publisher/editor.

All Rights Reserved.

Printed by
Green ThinkerZ
#530, B-4, Western Towers, Sector 126, Greater Mohali, Punjab (140301) – India

i
Awesome React.js

Acknowledgements
Many individuals share credit for this book’s preparation. We extend our sincere
thanks to Late Prof. A.D.Shinde, the Founder Director and Managing Trustee who has been a
constant source of inspiration for us throughout our career. His support is really a driving
force for us. Also, we would like to thank Dr.R.A.Shinde, Hon’ble Secretary, CSIBER for his
whole hearted support and continuous encouragement. We take this opportunity to thank
Dr.V.M.Hilage, Former Director and Academic Advisor, SIBER, for showing a keen interest
in the matter of this book and extending all support facilities for the in-timely completion of
this book. The material covered in this book is a systematic effort taken towards solving the
various queries which we received from our students time to time, during our 20+ years
tenure of teaching Java at PG level. Last but not the least we thank all faculty members and
non-teaching staff of department of computer studies, CSIBER, Kolhapur and department of
Computer Science, Shivaji University, Kolhapur who have made contribution to this book
either directly or indirectly.

Dr. Poornima G. Naik


Dr. Kavita S. Oza

ii
Awesome React.js

Preface
It gives us an immense pleasure to bring out a book entitled ‘Awesome React.js (Unleash the
Power of Modern UI Building)’. React.js offers a component-based architecture, efficient
rendering through the Virtual DOM, a declarative syntax, a thriving ecosystem, and cross-
platform capabilities. These factors contribute to its significance in the industry and make it
an attractive choice for developers aiming to build high-quality, scalable, and performant user
interfaces. The importance of React.js in the industry is further emphasized by its widespread
adoption by large tech companies, startups, and enterprises. It is a sought-after skill for front-
end and full-stack developers, and proficiency in React.js often enhances employability and
placement opportunities. Being well-versed in React.js can open doors to a wide range of job
opportunities in companies that build web and mobile applications.
React.js is continuously evolving, with regular updates and improvements from the React
team and the community. By learning React.js, you acquire valuable skills that can adapt to
future developments and stay relevant in a fast-paced industry. React.js has a shallow
learning curve, making it relatively accessible for developers to get started. The
documentation and resources available for learning React.js are extensive, and the
community is active and supportive. React.js offers valuable skills and knowledge that are in
high demand in the industry. It empowers computer science graduates to excel in front-end
development, full-stack development, and mobile app development. With its strong
community support, React.js ensures continuous learning and growth in the ever-evolving
field of web development.

How this book is organized


Chapter 1 focuses on pre-requisites required for building fully functional React.js
applications. Features of React.js and the components which are crucial for understanding the
structure of React.js application are discussed at length. The relative comparison and
differences between the contemporary and related technologies such as Angular.js, Vue.js,
React Native are highlighted. The chapter concludes with the Structure and Application
Architecture of React.js Application
Chapter 2 unleashes the intricacies involved in the life cycle of a React.js application. The
component life cycle methods and the different phases in component life cycle, initial phase,

iii
Awesome React.js
mounting, updating and unmounting phases along with order of execution of methods in each
phase are discussed in depth.
Chapters 3 is crucial to the understanding of workflow in a typical React.js application. The
chapter highlights significance of JSX in rendering components on UI, setting up of
development environment, using CRA tool which significantly simplifies the development of
React.js applications. The other important topics covered in the chapter are React.js folder
structure along with in-depth description of different file types and their contents, role of
virtual DOM in performance boosting and React.js application execution steps.
Chapter 4 is completely devoted to understanding of components, the basic building blocks
of React.js. Different types of components, stateless functional components and stateful class
components are discussed along with suitable demonstrations for state management and using
props, default props for communication.
Event handling is crucial for injecting interactivity into otherwise static application.
Considering the importance of event handling Chapter 5 provides an overview of synthetic
events in React.js. Different approaches to event handling such as using regular function
expressions, arrow functions, binding event to an event handler are given due credit. The
noteworthy topics of the chapter are using react snippets for auto code generation and
different mechanisms for importing, exporting the components and conditional rendering in
React.js.
Styling helps create visually appealing and aesthetically pleasing websites or applications.
Effective styling can significantly impact the user experience by improving usability and
readability. To enable the user to achieve this Chapter 6 discusses the techniques for adding
style to React components, conditionally applying the styles, applying multiple and inline
Styles and exploring CSS Modules in detail.
The final Chapter 7 provides an in-depth understanding of React forms. Relative comparison
between controlled and uncontrolled components and basics of form handling are provided.

The content of this book is derived from different sources available on Internet few of which
are listed at the end in a ‘references’ section.

Dr. Poornima G. Naik


Dr. Kavita S. Oza

iv
Awesome React.js

Contents
Chapter Page No.

1. Embracing the Essentials for React.js


1.1 Pre-requisites for Building React.js Applications and 01
Introduction
1.2 React.js Features 03
1.3 React Components 13
1.4 Difference Between Angular.js and React.js 15
1.5 Difference between React.js and React Native 20
1.6 React.js Vs. Vue.js 24
1.7 Exploring DOM in React – Real DOM Vs. Virtual DOM 25
1.8 Comprehending JSX 30
1.9 Structure and Application Architecture of React.Js Application 37
Components
2. Demystifying React.js Life Cycle
2.1 React Component Life Cycle 45
2.2 Life Cycle Methods 47
2.3 Initial Phase 47
2.4 Mounting Phase 49
2.5 Updating Phase 61
2.6 Unmounting Phase 65
3. Unveiling the Symphony of React.js Concepts
3.1 Exploring React JSX 67
3.2 Exploring the First React.js Application 74
3.3 React.js Application Folder Structure 78
3.4 React.js Application Execution Steps 83
3.5 React DOM Package 86
3.6 Setting Up of Development Environment for React.js 103
3.7 Developing a First React.js Application Using create-react-app 106

v
Awesome React.js
(CRA Tool)
4. Harnessing the Power of Components in React.js
4.1 Creating Components in React.js 112
4.2 Types of Components in React.js 113
4.2.1 Stateless Functional Components 113
4.2.2 Stateful Class Components 115
4.3 Hands on Sessions with Functional and Class Components 123
4.4 Constructor in a React 126
4.5 Defining State in Class Component 130
4.6 More on Props in React 143
4.7 Default Props 145
4.8 Relative Comparison Between Props and State 151
4.9 FAQs on Props and State 152
4.10 Combining State and Props 165
5. Mastering the Basics of Event Handing in React.js
5.1 Exploring React Events 212
5.2 Synthetic Event in React 212
5.3 Event Handling with Regular Function Expressions Without 217
Using State
5.4 Event Handling in Functional Component 219
5.5 Event Handling with Regular Function Expressions Using State 222
setState() is invoked Asynchronously
5.6 Event Handling Using Arrow Functions 229
5.7 Event Handling in Class Components 232
5.8 Binding Event Handler to an Event in React.js 237
5.9 Rendering a List in React 242
5.10 A Note on ‘export default’ Keyword 243
5.11 React Snippets 253
5.12 Exploring Conditional Rendering in React 257
5.13 List Rendering Revisited 271
6. Styling React Components
6.1 Adding Style to React Components 281

vi
Awesome React.js
6.2 Conditionally Applying the Styles 282
6.3 Applying Multiple Styles 284
6.4 Applying Inline Styles 286
6.5 Exploring CSS Modules 289
7. Exploring React Form
7.1 Types of Controls in React 295
7.1.1 Uncontrolled Components 297
7.1.2 Controlled Components 301
7.1.3 Differences Between Controlled and Uncontrolled 308
component
7.2 Basics of Form Handling in React.js 309
7.3 Submitting Form Data 311
References 324

vii
Awesome React.js

Chapter 1
Embracing the Essentials for React.js
1.1 Pre-requisites for Building React.js Applications and Introduction
Few pre-requisites required for understanding React.js concepts are listed below:
● HTML, CSS
● JavaScript ES6 specification. (ECMAScript)

React.js is a powerful JavaScript library specifically designed for creating visually appealing
and interactive user interfaces. Its core strength lies in the ability to build reusable UI
components, allowing developers to efficiently manage and organize their code.

One of the standout features of React.js is its declarative approach, where developers describe
the desired UI state and React takes care of updating the actual UI to match that state. This
simplifies the development process and enhances code readability tremendously.

Moreover, React.js boasts a robust ecosystem that facilitates seamless integration with other
frameworks and libraries. This flexibility enables developers to leverage existing tools and
technologies while incorporating React.js into their projects which further enhances the
learning curve.

With React.js, the focus is primarily on the presentation or view layer of an application,
providing a layer of abstraction that doesn't impose any assumptions or limitations on the rest
of the application stack. This makes React.js a versatile choice for building user interfaces
across a wide range of technology stacks.
Note: React.js operates only in the view layer of the application stack.
Note: React.js is not a framework.

React.js places a primary emphasis on constructing visually engaging and high-performance


user interfaces. To accomplish this, it utilizes a concept called the virtual DOM, which
outperforms the regular DOM in terms of speed and efficiency. React.js is widely employed
in developing front-end web applications. One of the key benefits of React.js is its ability to
enhance code readability through the utilization of component and data patterns. Components
allow for modular and reusable code structures, making it easier to manage and maintain

1
Awesome React.js
complex UIs. The data patterns, such as unidirectional data flow, simplify the understanding
of how data moves through the application, leading to cleaner and more maintainable code.
By combining these features, React.js provides developers with a robust toolkit for creating
rich and performant user interfaces, while at the same time promoting code organization,
reusability, and improved overall readability.

DOM (Document Object Model)

The Document Object Model (DOM) is an in-memory representation of a web page's


structure and content. When a web page is loaded into the browser's memory, the browser
creates a hierarchical object structure referred to as DOM, which mirrors the elements present
in the HTML. One of the notable characteristics of the DOM is its ability to dynamically
update the data of the elements in response to user interactions. Whenever an end user
modifies an HTML element, the DOM is updated to reflect those changes in the underlying
data. However, the major drawback of the DOM is that each time any modifications are made
to the web page, the entire DOM is recreated from scratch. This process can adversely impact
the performance of the application, particularly when dealing with complex or frequently
changing web pages.

To address this performance concern, React.js utilizes a virtual DOM. The virtual DOM is a
lightweight, in-memory representation of the actual DOM. It acts as a reconciliation layer
between the application's state and the actual DOM, optimizing the process of updating the
user interface.

By leveraging the virtual DOM, React.js intelligently identifies and updates only the specific
parts of the DOM that have changed, rather than recreating the entire DOM tree. This
approach significantly improves the performance of React.js applications, as it minimizes
unnecessary DOM manipulations and renders.

Hence React.js mitigates the performance impact caused by the frequent recreation of the
DOM by employing a virtual DOM, resulting in more efficient updates and smoother user
experiences.

Virtual DOM by React.js


React.js addresses the drawbacks of traditional DOM manipulation with the concept of
virtual DOM. It introduces a component-based approach, allowing developers to break down

2
Awesome React.js
their applications into smaller, reusable building blocks. What sets React.js apart is its
utilization of a virtual DOM instead of directly interacting with the browser's Document
Object Model.
With React.js, modifications to the application's data flow still follow the conventional
pattern, but they don't immediately impact the actual DOM. Instead, React.js operates on a
virtual representation of the DOM, which exists solely in memory. This means that changes
are resolved on this virtual DOM before being applied to the browser's DOM.

By employing this virtual DOM mechanism, React.js optimizes the process of updating the
user interface. After the virtual DOM is updated, React.js intelligently determines the
necessary changes to be made in the browser's DOM. This approach minimizes unnecessary
updates and enhances overall performance. When developing with React.js, we write
components that represent the desired state of the UI, rather than directly manipulating the
DOM. React.js takes care of translating these virtual components into the corresponding
elements in the actual DOM.

Thus, React.js revolutionizes web development by introducing a virtual DOM that operates in
memory. This approach enhances performance by optimizing the way changes are applied to
the browser's DOM, while still adhering to the familiar data flow patterns. The result is a
more efficient and maintainable way of building web applications.

1.2 React.js Features

JSX Components
Declarative
Syntax

Virtual
Features of React.js Performance
DOM

One Way
Cross-platform
Data Simplicity
Binding Compatibility

3
Awesome React.js
React.js is rapidly emerging as the leading JavaScript framework. With its exceptional
capabilities, React.js has become a cornerstone of the front-end ecosystem, revolutionizing
the way we build user interfaces. Let's delve into some of its standout features:

Declarative Syntax: React.js's declarative approach allows developers to describe how the UI
should look based on the application state. This results in code that is more intuitive and
easier to reason about.

Component-Based Architecture: React.js encourages a modular and reusable approach by


breaking down the UI into small, self-contained components. This promotes code reusability,
maintainability, and scalability.

At the heart of React.js lies the concept of components. React.js applications are built by
assembling multiple components, with each component having its own distinct logic and
control. This modular approach not only promotes code organization but also offers the
advantage of reusability, making it easier to maintain and manage codebases, particularly in
larger-scale projects.

By breaking down the application into reusable components, developers can encapsulate
specific functionality and UI elements. This allows for better code separation, making it
simpler to understand, test, and modify individual components without affecting others.

The reusability of components is a powerful feature in React.js. It enables developers to


leverage existing components across different parts of the application, reducing redundancy
and promoting consistency. This approach saves time and effort by eliminating the need to
rewrite similar code for similar functionalities.

Moreover, component-based development in React.js enhances collaboration and team


efficiency. With well-defined and self-contained components, different team members can
work on different components simultaneously, allowing for parallel development and
smoother integration

React.js empowers developers to build applications using a modular component-based


approach. This approach promotes code reusability, simplifies maintenance, and improves
collaboration, making React.js an ideal choice for scalable and efficient web development.

4
Awesome React.js
Virtual DOM: By leveraging a virtual representation of the DOM, React.js optimizes
rendering performance. It intelligently determines and applies only the necessary updates to
the actual DOM, resulting in a smoother and more efficient user experience.

A virtual DOM object serves as a mirror image of the original DOM object in a web
application. It operates on the principle of one-way data binding, wherein any modifications
made to the application trigger a re-rendering of the entire user interface within the virtual
DOM.

The virtual DOM then performs a comparison between the previous representation and the
updated representation of the DOM. This intelligent diffing process identifies the specific
elements that have changed.

Once the diffing is complete, the real DOM is updated with only the necessary changes,
sparing unnecessary updates and optimizing memory usage. This efficient approach
eliminates redundant operations, resulting in a faster and more responsive application.

By utilizing a virtual DOM, React.js minimizes the direct manipulation of the real DOM and
selectively applies updates, reducing both computational overhead and memory consumption.
This approach ensures that resources are utilized optimally, leading to improved application
performance and a more efficient user experience.

Unidirectional Data Flow (One Way Data Binding): React.js enforces a unidirectional data
flow, ensuring that data changes are predictable and easier to debug. This improves code
maintainability and reduces the likelihood of bugs.

React.js embraces the principle of unidirectional data flow, also known as one-way data
binding. This design choice offers several valuable benefits, granting developers greater
control over their applications. By enforcing a one-way data flow, React.js promotes
immutability within components, ensuring that the data contained within them remains
unaltered.

The unidirectional data flow pattern enhances predictability and maintainability. It simplifies
debugging and reduces the chances of unexpected side effects, as data changes can be traced
to a single source. This streamlined flow also facilitates efficient state management, allowing
developers to pinpoint precisely where and how data is modified.

5
Awesome React.js
By adhering to the unidirectional data flow and utilizing patterns like Flux, React.js
empowers developers to create more robust and efficient applications. The clear data flow
direction and the immutability of components ensure better control and maintainability,
ultimately leading to enhanced application performance and flexibility.

JSX:

JSX, an acronym for JavaScript XML, is a powerful syntax extension in the realm of
JavaScript. Specifically tailored for React.js, JSX introduces an XML or HTML-like syntax,
enabling seamless integration of UI components into JavaScript code. React.js's JSX syntax
enables developers to write HTML-like code directly in JavaScript, enhancing code
readability and making it more expressive. It reduces the Spaghetti code.

With JSX, developers can write code that closely resembles HTML markup, making it more
intuitive and familiar. This syntax is then transpiled into JavaScript calls that correspond to
the React framework's functions and methods.

By extending ES6, JSX facilitates the harmonious coexistence of HTML-like text and
JavaScript code within a single file. This fusion enables developers to encapsulate their UI
components and logic in a concise and cohesive manner.

While not obligatory, using JSX is highly recommended when working with React.js. It
offers numerous benefits, including enhanced code readability, improved developer
productivity, and a more intuitive representation of the UI structure.

JSX acts as a bridge between HTML-like syntax and JavaScript code in React.js. Its ability to
blend XML or HTML-like syntax with JavaScript seamlessly empowers developers to create
elegant and expressive UI components with ease.

Rich Ecosystem: React.js enjoys a thriving ecosystem with a vast array of libraries, tools, and
community support. This ecosystem empowers developers to streamline development
processes, enhance productivity, and integrate seamlessly with other technologies.

Performance Optimization: React.js provides mechanisms like lazy loading, code splitting,
and memorization to optimize performance. This enables faster rendering and improved user
interactions.

6
Awesome React.js
Cross-Platform Compatibility: React.js is not limited to web development alone. It can be
used to build native mobile applications using React Native, expanding its reach to multiple
platforms.

Simplicity

React.js leverages the power of JSX files, revolutionizing the way applications are developed
by introducing simplicity and enhanced code comprehension. JSX combines HTML-like
syntax with JavaScript, resulting in a concise and intuitive coding experience.

With React.js's component-based architecture, the code becomes inherently reusable. By


breaking down the application into smaller, self-contained components, developers can
encapsulate specific functionality and easily reuse them across different parts of the
application. This reusability not only promotes code organization but also enhances
development efficiency, as common components can be leveraged without duplicating code.

The use of JSX in React.js further amplifies its simplicity and learnability. The familiar
HTML-like syntax allows developers to seamlessly integrate UI elements and logic within
their JavaScript code. This cohesion between markup and functionality makes it easier to
conceptualize and understand the structure of the application, enabling faster development
and debugging cycles.

By embracing the component-based approach and JSX, React.js empowers developers to


write elegant, reusable, and easy-to-understand code. This streamlined development
experience ultimately reduces complexity, promotes code maintainability, and accelerates the
learning curve of React.js.

Performance
Renowned for its exceptional performance, React.js outshines other frameworks available
today, thanks to its adept management of a virtual DOM. The DOM, a versatile cross-
platform programming API, handles HTML, XML, and XHTML. In React.js, the DOM is
ingeniously represented entirely in memory.
When developing components in React.js, we don't directly manipulate the actual DOM.
Instead, we construct virtual components that seamlessly transform into the DOM, yielding
enhanced speed and efficiency. This distinctive approach empowers React.js to intelligently
discern the necessary changes and selectively update specific elements within the real DOM.

7
Awesome React.js
By leveraging the virtual DOM, React.js optimizes performance in a multitude of ways. It
efficiently reconciles the previous and updated DOM representations, identifying targeted
modifications and applying them judiciously. This process minimizes redundant operations,
culminating in a fluid and agile user experience.

Furthermore, React.js's adept management of the virtual DOM promotes resource


optimization, mitigating unnecessary computations and maximizing responsiveness. With its
strategic diffing mechanism, React.js ensures that the rendering process remains streamlined,
enabling faster updates and minimizing latency.

The virtuosic handling of the virtual DOM in React.js elevates its performance above other
frameworks. By deftly converting virtual components into the DOM, React.js fosters a
seamless and expeditious development experience, propelling the application towards
smoother execution and superior user satisfaction.

Pros and Cons of React.js


In today's landscape, React.js stands as a prominent and widely adopted open-source
JavaScript library. It empowers developers to craft remarkable web applications with minimal
effort and coding intricacies. The primary aim of React.js revolves around building highly
performant User Interfaces (UI) that deliver enhanced speed and responsiveness.

Advantages Offered By React.js


Here are some key advantages offered by React.js:
Accessibility and Ease of Adoption: React.js is renowned for its accessibility and ease of
adoption. Developers with a background in JavaScript can quickly grasp React's concepts and
dive into building web applications effortlessly.

Streamlined Dynamic Web Development: React.js simplifies the creation of dynamic web
applications by offering a streamlined approach. With React, developers can achieve complex
functionality with concise and elegant code, minimizing the effort required to build
interactive user interfaces.

Component Reusability for Efficient Development: React.js revolves around the concept of
reusable components, empowering developers to create modular and maintainable code. By
reusing components across different parts of an application, development time is reduced, and

8
Awesome React.js
code consistency is improved, resulting in more efficient and scalable development
processes.

Performance Optimization through Virtual DOM: React.js leverages the virtual DOM, a
lightweight representation of the browser's DOM, to enhance performance. By efficiently
comparing and updating only the necessary components, React minimizes unnecessary re-
rendering, leading to improved performance and a smoother user experience.

Robust Developer Tools for Enhanced Productivity: React.js offers a suite of powerful
developer tools that facilitate debugging, inspection, and performance optimization. These
tools provide deep insights into component hierarchies, state changes, and performance
bottlenecks, empowering developers to deliver high-quality applications with enhanced
productivity.

Hence in brief React.js combines accessibility, streamlined development, component


reusability, performance optimization through the virtual DOM, and robust developer tools to
offer a powerful and efficient framework for building modern web applications. These
advantages contribute to faster development cycles, improved code quality, and an
exceptional end-user experience.

Disadvantages of React.js
Few disadvantages offered by React.js are enumerated below:
Ongoing Learning Curve: The fast-paced nature of React.js and its evolving ecosystem can
present a challenge for developers. Keeping up with the latest updates and best practices
requires continuous learning and adaptation, which may be demanding for some developers.

Limited Official Documentation: With the rapid advancements in React.js, official


documentation may not always keep pace. This can make it challenging for developers to
find comprehensive and up-to-date resources. However, the active React.js community often
fills this gap by providing valuable insights and tutorials.

Focused on the View Layer: React.js is primarily focused on the user interface (UI) layer of
applications, offering robust tools for building UI components. However, developers may

9
Awesome React.js
need to integrate additional libraries or frameworks to handle other aspects such as routing
and state management.

Server-Side Rendering Complexity: While React.js allows for server-side rendering (SSR) to
improve SEO friendliness and initial page load times, setting up and configuring SSR can be
complex. Developers need to invest additional time and effort to ensure proper
implementation.

Build Tooling Complexity: React.js projects often require build tools such as Webpack or
Babel to transpile and bundle code. Configuring and optimizing these build tools can be
intricate, especially for developers new to React.js or complex project setups.

Steeper Learning Curve for Beginners: React.js may have a steeper learning curve for
beginners compared to simpler frameworks or libraries. Its concepts, including JSX syntax
and component-based architecture, may take time to grasp fully.

Despite these challenges, React.js remains a popular choice for building modern web
applications. Its benefits, such as component reusability, performance optimization, and a
thriving community, outweigh the disadvantages for many developers. With dedication and a
willingness to learn, developers can harness the power of React.js to create robust and
dynamic user interfaces.

Key Features Supported By React.js and Merits


Seamless Learning and Usage:
React.js boasts a user-friendly learning curve, making it highly accessible for developers.
Abundant documentation, tutorials, and training resources are readily available, enabling
individuals familiar with JavaScript to swiftly grasp and employ React.js for web application
development. Serving as the view component in the MVC (Model-View-Controller) model,
React.js is recognized as one of the prominent JavaScript frameworks. Although not
encompassing the entirety of a framework's features, React.js excels as an open-source
JavaScript library specifically designed for User Interface (UI) development, enhancing task
execution efficiency.

10
Awesome React.js
Streamlining Dynamic Web Application Development
React.js simplifies the process of developing dynamic web applications that involve handling
HTML strings. Previously, accomplishing this task required complex coding techniques.
However, React.js has effectively addressed this challenge by providing a more streamlined
approach. With React.js, developers can achieve enhanced functionality while writing less
code.
A key feature that enables this efficiency is JSX (JavaScript Extension). JSX introduces a
unique syntax that allows developers to incorporate HTML quotes and HTML tag syntax for
rendering specific subcomponents. This not only facilitates the creation of dynamic web
applications but also supports the creation of machine-readable code.
In essence, React.js empowers developers to create dynamic web applications with ease,
reducing the complexity of handling HTML strings. By leveraging JSX and its intuitive
syntax, developers can efficiently build robust and interactive user interfaces, making the
development process more efficient and productive.

Modular and adaptable building blocks for streamlined web development


A React.js web application comprises multiple components, each with its own logic and
controls. These components serve the purpose of generating small, reusable fragments of
HTML code that can be employed across various sections of the application. By utilizing
reusable code, the development and maintenance of apps become more manageable. These
components can also be nested within one another, enabling the construction of intricate
applications through the combination of simple building blocks. React.js leverages a virtual
DOM-based mechanism to efficiently update the HTML DOM by modifying specific
elements rather than reloading the entire DOM every time, resulting in enhanced
performance.

Performance Enhancement
React.js revolutionizes performance with its virtual DOM, an in-memory representation of
the web browser's DOM. By eliminating direct writes to the DOM, React.js enables the
creation of virtual components that seamlessly translate into the actual DOM, resulting in
unparalleled smoothness and exceptional speed for applications.

11
Awesome React.js
Efficient Development Tools Harnessing the Power of React.js
React.js has garnered widespread acclaim thanks to its robust arsenal of convenient tools.
These tools serve as invaluable aids for developers, offering enhanced understanding and
simplified workflows. Among these tools, the React Developer Tools stand out, as they come
in the form of Chrome and Firefox extensions. With these tools, developers can effortlessly
inspect the hierarchies of React components within the virtual DOM. Furthermore, they
enable the selection, examination, and editing of specific components' current props and state,
empowering developers with unprecedented control and efficiency.

Empowering SEO-friendly web development.


React.js addresses the SEO challenge faced by traditional JavaScript frameworks, ensuring
smooth navigation on search engines. By enabling server-side rendering, React.js
applications generate a regular web page where the virtual DOM is rendered and delivered to
the browser. This seamless process allows search engines to effortlessly crawl and index
React.js applications, alleviating concerns expressed by web developers.

Versatile JavaScript library.

React.js has become the top choice for web developers today due to its exceptionally
comprehensive JavaScript library. This library empowers developers with unparalleled
flexibility, allowing them to customize and shape their projects precisely according to their
preferences and requirements.

Seamless Code Testing


React.js applications excel in testability, providing developers with a seamless environment
for testing and debugging their code using native tools.

Few Downsides of React.js


The Rapid Pace of Development
The rapid pace of development in React.js brings both advantages and challenges. On the
downside, some developers may find it uncomfortable to frequently adapt to new
methodologies and techniques. Keeping up with the continuous updates can be demanding,
requiring constant skill upgrading and learning of new approaches. However, this dynamic

12
Awesome React.js
environment also presents an opportunity for growth, motivating developers to stay updated
and continually expand their skill set to embrace the latest innovations.

Poor Documentation
One common drawback observed in rapidly evolving technologies, such as React, is the
challenge of keeping up with the constant updates. The fast-paced nature of React's
advancements often results in limited availability of comprehensive documentation. In
response, developers take matters into their own hands by crafting project-specific
instructions, adapting to the evolving releases and tools. This proactive approach ensures
effective utilization of the latest features and enhancements in their projects.

UI Layer
React.js specializes in the UI layer of applications, excelling in its domain. However, to
achieve a comprehensive tooling set for development, additional technologies need to be
carefully chosen to complement React.js. This ensures a holistic approach to building robust
and feature-rich projects.

JSX Poses a barrier


React.js embraces JSX, a powerful syntax extension that seamlessly blends HTML with
JavaScript. While JSX offers numerous benefits, there is a segment of the development
community that perceives it as a potential barrier, particularly for newcomers. Some
developers express concerns regarding its learning curve and perceived complexity.

React Elements
React element is a JavaScript representation of HTML DOM. React provides an API,
React.createElement to create React Element.

1.3 React Components


Components in a React application play a pivotal role as they serve as the fundamental
building blocks. These small logical groups of code are carefully crafted and encapsulated
entities that operate independently of one another. They possess their own distinct space,
maintaining a sense of autonomy within the application's architecture. This isolation ensures
that components remain self-contained and can easily be modified.

13
Awesome React.js
One of the remarkable aspects of React components lies in their reusability. Each component
is meticulously designed to fulfil a specific purpose, yet it can be employed in multiple
contexts throughout the application. This reusability eliminates the need for redundant code,
promoting efficiency and maintainability. By encapsulating specific functionalities within
components, developers can leverage their power across various user interfaces, creating a
cohesive and scalable React application.

In essence, every user interface element in a React app, be it a simple button or a complex
form, is meticulously crafted as an individual component. These components, with their
modular nature, collectively form the foundation of the application's interface, enabling
seamless composition and extensibility. The ability to harness the full potential of
components as reusable entities empowers developers to create polished and robust
applications that can adapt and evolve with ease.

Components are of two types:


● Class components and
● Functional components.

Class components are stateful since they maintain their ‘state’ to change the user interface.
Functional components are stateless components. They act like a JavaScript function that
takes an arbitrary parameter called ‘props’ which stands for properties.
React Hooks have been introduced in the later version of React.js to access states in
functional components.
React components serve as the fundamental cornerstone of React applications, allowing for
the creation of dynamic and interactive user interfaces. They leverage the power of React
Elements and JSX, enabling developers to craft visually appealing and intuitive UI designs.

A React Component can take the form of a JavaScript class, extending the base React
Component class, or a pure JavaScript function. Regardless of the implementation approach,
components possess crucial attributes such as properties, state management capabilities,
lifecycle methods, and event handlers.

14
Awesome React.js
By utilizing properties, components can receive input values and configuration data, allowing
for customization and flexibility. State management empowers components to maintain their
own internal data, enabling them to adapt and respond to user interactions and application
logic. Lifecycle methods grant developers fine-grained control over component initialization,
updates, and destruction, facilitating smooth and efficient execution of code at various stages.

React components excel in their ability to handle events, responding to user actions such as
button clicks, form submissions, or user input. This interactivity fosters engaging user
experiences and enables components to execute both simple and intricate logic, catering to a
wide range of application requirements.

Overall, React components provide a robust and scalable foundation for building polished
applications. Their versatility, coupled with the seamless integration of JavaScript and JSX,
empowers developers to create dynamic, feature-rich interfaces that captivate users and
showcase the full potential of React.

1.4 Difference Between Angular.js and React.js


Angular.js
Angular.js is an exceptional open-source JavaScript framework that empowers developers to
construct dynamic web applications with remarkable proficiency. Its primary focus lies in the
creation of Single Page Applications, seamlessly integrating HTML and JavaScript for a
seamless and efficient development process.

One of Angular.js' notable features is its effortless integration into an HTML page using a
simple <script> tag. This straightforward inclusion ensures that developers can swiftly
leverage the power of Angular.js within their projects.

What truly distinguishes Angular.js is its ability to enhance HTML's capabilities through
directives. These directives provide built-in attributes, effortlessly augmenting the
functionality and interactivity of web applications. By seamlessly combining HTML and
directives, Angular.js enables developers to create highly expressive and intuitive user
interfaces.

15
Awesome React.js
Additionally, Angular.js boasts a robust data binding mechanism. Through the use of
expressions, developers can effortlessly establish a connection between their data model and
HTML elements, facilitating automatic synchronization and ensuring real-time updates. This
powerful feature empowers developers to create dynamic and responsive web applications
without excessive manual intervention.

In essence, Angular.js stands as a refined and sophisticated framework, allowing developers


to build cutting-edge web applications with exceptional ease. By seamlessly merging HTML,
JavaScript, directives, and data binding, Angular.js offers an unparalleled development
experience, enabling developers to bring their visions to life in a polished and efficient
manner.

Features Supported By Angular.js


Angular.js excels in providing an array of exceptional features that contribute to its popularity
and efficacy in web application development. Let's delve into these features.

Two-Way Data Binding: Angular.js leverages the power of two-way data binding,
seamlessly synchronizing data between the model and view components. This automatic and
bidirectional communication ensures that any changes made in the model are instantaneously
reflected in the view, and vice versa.

POJO Model: Angular.js adopts the concept of a POJO (Plain Old JavaScript Object) model,
which promotes well-structured and intuitive objects. This approach enhances Angular.js's
self-containment and user-friendly nature, simplifying the development process.

Model-View-Controller (MVC) Architecture: Angular.js embraces the renowned MVC


design pattern, offering developers a robust framework for web application development. Its
MVC architecture is flexible, dynamic, and facilitates the creation of client-side applications
in a streamlined manner.

Built-in Services: Angular.js comes bundled with a wealth of built-in services, such as the
HTTP service, which simplifies making XMLHttp requests. These services empower

16
Awesome React.js
developers by handling common tasks and facilitating seamless interaction with external
resources.
HTML-based User Interface: Angular.js capitalizes on the inherent strengths of HTML to
create user interfaces. Its declarative nature and concise tags enhance readability, resulting in
well-organized, visually appealing, and structurally sound user interfaces.

Dependency Injection: Angular.js incorporates a powerful dependency injection subsystem,


enabling developers to effortlessly create, comprehend, and test applications. This feature
promotes code modularity, maintainability, and overall application efficiency.

Vibrant Community Support: Angular.js benefits from a vibrant community, fostered by its
association with Google. This strong community provides extensive support and resources,
with a multitude of forums available to address maintenance concerns and assist developers
in troubleshooting their queries.

Routing: Angular.js simplifies routing, facilitating seamless transitions between different


views within a single-page application. By dynamically loading content on the same page
while updating the URL, Angular.js enhances user experience by eliminating the need for
frequent page redirects.

Hence Angular.js stands as a refined and comprehensive framework, offering features such as
two-way data binding, a POJO model, MVC architecture, built-in services, HTML-based UI,
dependency injection, vibrant community support, and efficient routing. These features
collectively empower developers to craft sophisticated and responsive web applications with
grace and proficiency.

React.js

React.js is an exceptional open-source JavaScript library meticulously designed to empower


developers in crafting captivating user interfaces for Single Page Applications. It places
utmost emphasis on the view layer of an application, seamlessly integrating with other
technologies to create a seamless user experience. React.js introduces a novel concept known
as ‘components’ enabling developers to compose intricate UIs by encapsulating small, self-
contained pieces of code.

17
Awesome React.js
At the heart of React.js lies the power of components. These self-contained entities
encapsulate HTML code, specifying the desired visual elements and functionalities of the
user interface. By breaking down the UI into reusable components, React.js promotes code
modularity, reusability, and maintainability, making development more efficient and scalable.

These React.js components are seamlessly rendered onto an HTML document, serving as the
foundation where they harmoniously unite to form the complete user interface. By skilfully
merging the logical and visual aspects of components with the HTML document, React.js
creates a cohesive and engaging user experience.

In essence, React.js stands as an elegant and refined JavaScript library that elegantly
addresses the view layer of Single Page Applications. Through the power of components,
React.js empowers developers to effortlessly construct intricate and visually stunning user
interfaces. By seamlessly integrating these components into an HTML document, React.js
ensures a seamless and captivating user experience that captivates users and propels
application development to new heights.

Features Supported By React.js


React.js encompasses an impressive array of features that contribute to its efficacy in web
application development. Let's explore these features.

JSX: React.js introduced JSX, a powerful syntactical extension that seamlessly combines
HTML-like text with JavaScript code. This unique blend enhances code expressiveness and
readability, enabling developers to create intuitive and concise React components.

Components: At the core of React.js lies its component-based architecture. React.js


applications are built by assembling multiple reusable components, each encapsulating its
own logic and functionality. This modular approach promotes code reusability,
maintainability, and scalability, facilitating efficient development in projects of any size.

One-Way Data Binding: React.js adheres to a unidirectional data flow, ensuring a clear and
predictable flow of data throughout the application. By maintaining immutability and
restricting data changes within components, React.js enhances data control and simplifies
state management, resulting in more stable and manageable applications.

18
Awesome React.js
Virtual DOM: React.js leverages a virtual DOM, which serves as a lightweight representation
of the actual DOM. When updates occur, React.js efficiently compares the previous and new
versions of the virtual DOM, identifying the minimal changes needed to update the real
DOM. This approach minimizes expensive DOM operations, resulting in improved
performance and responsiveness.

Simplicity: React.js embraces a philosophy of simplicity, making it accessible and intuitive


for developers. Its use of JSX streamlines the creation of components, enabling developers to
seamlessly blend HTML and JavaScript. The component-based approach enhances code
organization and reusability, reducing complexity and promoting code readability.

Performance: React.js is renowned for its exceptional performance characteristics. By


employing a virtual DOM and optimizing update processes, React.js minimizes unnecessary
re-rendering and DOM manipulation. This efficient approach leads to faster rendering,
smoother user interactions, and improved overall application performance.

In essence, React.js stands as a refined and powerful library, offering features such as JSX,
component-based architecture, one-way data binding, virtual DOM, simplicity, and superior
performance. These features collectively empower developers to create scalable,
maintainable, and high-performing web applications, while fostering an enjoyable and
efficient development experience.

Angular.js Vs. React.js


Feature Angular.js React.js
Company Google Facebook
Rendering HTML, JavaScript JSX
Language
Framework MVC Framework JavaScript Framework
Rendering Client-Side Server-Side
DOM Employed Regular DOM Virtual DOM
Data Binding Bi-directional Uni-directional
Performance Slow Fast owning to virtual DOM

19
Awesome React.js
Learning curve Angular.js has a steeper React.js has a simpler and more
learning curve. focused API, making it relatively
easier to learn
File Size Larger impacting the initial Compact, small bundle sizes with
load time of the application. potentially better performance.
Mobile Angular.js has a built-in React.js has React Native, a popular
Development framework called Ionic, which framework for building native mobile
provides tools for building applications using JavaScript and
hybrid mobile applications React components.
using web technologies.

1.5 Difference between React.js and React Native


React Native
React Native is a cutting-edge open-source JavaScript framework that empowers developers
to build robust mobile applications for iOS, Android, and Windows platforms. Unlike
traditional approaches, React Native harnesses the power of JavaScript to create cross-
platform apps, eliminating the need for separate development efforts.

What sets React Native apart is its utilization of native components rather than web
components as the building blocks. By leveraging the platform's native capabilities, React
Native delivers high-performance, responsive, and visually stunning user experiences that
closely resemble those of native apps.

With React Native, developers can tap into the full potential of mobile platforms, unlocking a
wealth of features such as push notifications, GPS functionality, camera access, and more. By
seamlessly integrating with the native APIs, React Native provides a bridge between
JavaScript and native code, enabling the creation of truly native mobile apps.

One of the key advantages of React Native is its ability to streamline the development
process. Developers can write code once and deploy it across multiple platforms, saving
valuable time and resources. This approach also ensures code consistency, simplifies
maintenance, and facilitates rapid prototyping and iteration.

20
Awesome React.js
In addition, React Native benefits from a vibrant and enthusiastic community. This thriving
ecosystem offers an extensive collection of pre-built components, libraries, and tools that
accelerate development and foster code reuse. Developers can tap into this rich resource pool,
enabling them to create feature-rich and visually appealing mobile apps in a fraction of the
time.
In brief, React Native is a game-changing JavaScript framework that revolutionizes mobile
app development. By leveraging native components and cross-platform capabilities, it
enables developers to create high-performance mobile apps with stunning user experiences.
With its streamlined development process and vibrant community support, React Native
empowers developers to bring their mobile app ideas to life quickly and efficiently.

Advantages offered by React Native


React Native offers numerous advantages for building mobile applications, making it a
preferred choice for many developers.
Cross-Platform Usage: React Native follows the principle of ‘Learn once, write everywhere’.
It empowers developers to create mobile apps that seamlessly run on both Android and iOS
devices, eliminating the need for separate development efforts for each platform.

Exceptional Performance: The code written in React Native is compiled into native code,
ensuring high performance on both operating systems. This enables apps to deliver a
consistent and efficient user experience across platforms.

JavaScript Development: React Native leverages the familiarity and versatility of JavaScript,
enabling developers to utilize their existing skills to build native mobile applications. This
reduces the learning curve and accelerates the development process.

Thriving Community: React Native benefits from a vast and active community of
developers. This community provides extensive support, resources, and guidance, making it
easier to find solutions and best practices for any challenges encountered during
development.

Hot Reloading: During the development phase, React Native offers the convenience of hot
reloading. This means that any changes made to the code are immediately reflected in the

21
Awesome React.js
app, allowing developers to see the results in real-time. It significantly enhances productivity
and speeds up the debugging process.

Continuous Improvement: React Native is continually evolving, and its community is


dedicated to enhancing the framework's capabilities. As new features and improvements are
introduced, developers can leverage the latest advancements and best practices to create
cutting-edge mobile applications.

Native Component Integration: React Native provides the flexibility to incorporate platform-
specific functionalities by writing platform-specific code. This allows developers to
seamlessly integrate native components that may not be readily available in the framework.

Long-Term Viability: Although React Native is developed by Facebook, its popularity and
widespread adoption make it highly unlikely for the project to be discontinued. As a result,
the framework is expected to thrive and receive ongoing support from the community,
ensuring its continued presence in the mobile development landscape.

In conclusion, React Native's cross-platform capabilities, performance, JavaScript


development approach, strong community support, hot reloading feature, continuous
improvement, native component integration, and long-term viability contribute to its appeal
as a powerful framework for building mobile applications.

Disadvantages of React Native


React Native: A Growing Framework with Advancements Ahead: React Native, although
relatively young in the world of Android and iOS development, is a dynamic framework that
is constantly evolving. As developers continually enhance its capabilities, React Native is
poised to overcome any potential limitations and deliver even better experiences for mobile
apps.

Navigating the Learning Curve: It's true that becoming proficient in React Native can pose a
challenge, particularly for newcomers to app development. However, with dedication,
determination, and access to quality learning resources, developers can conquer the learning
curve and unlock the immense potential of this versatile framework.

22
Awesome React.js

Balancing Security Considerations: React Native, being built on JavaScript and an open-
source foundation, warrants careful consideration when handling sensitive data, such as in
banking and financial applications. Engaging the expertise of security professionals and
evaluating the unique security requirements of your app will ensure a robust and protected
environment for confidential information.

Striving for Optimal Initialization: While React Native's initialization process may require
some additional time, especially on cutting-edge devices, developers are actively working
towards optimizing this aspect. By leveraging advancements in technology and employing
efficient strategies, initialization times can be minimized, leading to seamless and swift user
experiences.

React.js Vs React Native


Feature React.js React Native
Type It is used for developing web It is used for developing mobile
application. application.
Platform It can be executed on versatile Platform specific, designed for
platforms. Targets web bowser. mobile applications. Targets iOS and
android platforms.
Navigation It employs React-router to It has in-built navigation library.
navigate through different web
pages
Security High Low
Rendering Employs virtual DOM for Employs API to render code for
rendering on the browser. mobile applications.
UI React.js employs functional and React Native uses native
class components to render components and APIs to render UI
HTML for UI. elements
Application Employs Single Page Employs multi page application
Application approach approach.
Performance React.js applications run in web React Native apps leverage the

23
Awesome React.js
browsers and are subject to the native rendering capabilities of the
performance characteristics and underlying platform which allows
limitations of the browser's React Native to achieve high
rendering engine performance

1.6 React.js Vs. Vue.js


React and Vue stand out as two prominent JavaScript libraries that have become the
backbone of countless websites today. These frameworks possess their own distinct
advantages and considerations, and the choice between them ultimately depends on the
unique requirements of each business and use case.

React and Vue share fundamental similarities, including their component-based architecture,
usage of virtual DOM, employment of props, and support for Chrome Dev Tools, facilitating
effective debugging. However, they also exhibit noteworthy disparities that should be taken
into account.

React, renowned for its declarative syntax, offers a powerful and flexible framework. Its vast
community support contributes to an extensive ecosystem of libraries and resources, making
it highly adaptable to diverse project needs. React's emphasis on composition and reusability
makes it particularly suitable for complex, large-scale applications.

Conversely, Vue differentiates itself with an intuitive and user-friendly approach, featuring a
template-based syntax. Its gentle learning curve makes it accessible for developers of all
levels, and its comprehensive documentation further enhances its appeal. Vue seamlessly
integrates into existing projects, allowing for a gradual adoption process without requiring
substantial rewrites.

React excels in performance and handling vast amounts of data, while Vue prioritizes
simplicity and an enjoyable developer experience. React's widespread adoption by industry
leaders solidifies its position as a reliable choice, while Vue's focus on ease of use and
progressive integration makes it an attractive alternative.
Ultimately, the decision to opt for React or Vue depends on careful consideration of factors
such as scalability, project size, learning curve, and ecosystem support. By evaluating these

24
Awesome React.js
aspects thoughtfully, developers can make an informed choice, leveraging the strengths of
either React or Vue to create exceptional web experiences.

Feature React.js Vue.js


Language JSX HTML and JavaScript
Application Architecture Focuses on View layer of the MVC. Separates presentation
application. logic from business logic and
data logic
Performance Slow compared to Vue.js Faster
Size of Library Approx. 100 KB Approx. 60 KB
Support for third party Supports third party libraries Provides limited flexibility
libraries and seamless integration of compared to React.
other technologies
Data Binding Supports only one-way data Supports both one way and
binding. two-way data bindings.
Tooling support React has great tooling Provides limited tooling
support. It employs the third support as compared to
party CLI tool ‘create-react- React.
app’ for creating new apps
and components in a react
project.

1.7 Exploring DOM in React – Real DOM Vs. Virtual DOM


Real/Browser DOM
The term DOM, short for 'Document Object Model,' refers to a meticulously organized
representation of the HTML within a webpage or application. It provides a comprehensive
and structured view of the user interface (UI), effectively visualized as a sophisticated tree-
like data structure. This hierarchical arrangement captures the relationships and interactions
among the various elements, empowering developers to manipulate and navigate the UI with
precision and efficiency.
It is a structural representation of HTML elements of a web application.

25
Awesome React.js

When the state of an application's user interface (UI) changes, the DOM undergoes updates to
reflect those changes. However, this process of rendering and manipulating the DOM with
each modification can introduce performance considerations, potentially leading to decreased
efficiency and slower responsiveness.
In cases where the UI comprises numerous components and features a complex DOM
structure, updating the DOM becomes a more resource-intensive task. Re-rendering the DOM
to accurately represent the updated UI incurs computational costs, which can impact overall
performance.
The DOM, structured as a hierarchical tree-like data structure, encompasses nodes
representing each UI element within the web document. This organization enables efficient
navigation and manipulation of the UI. However, it also calls for careful attention to
performance implications when frequent modifications to the DOM are required.
In essence, while the DOM serves as a valuable representation of the UI and facilitates
dynamic updates, it is essential to strike a balance between maintaining accuracy and
optimizing performance. This delicate equilibrium ensures a seamless and responsive user

26
Awesome React.js
experience, especially when dealing with intricate UI components and a complex DOM
structure.

Updating the DOM


To modify the contents of the DOM, developers often utilize methods such as
'getElementById()' or 'getElementByClass()'. These methods allow for targeted access to
specific elements within the DOM, enabling efficient updates to the UI.

Whenever a change occurs in the application's state, the DOM is promptly updated to reflect
the corresponding modifications in the UI. This ensures that the user interface accurately
represents the current state of the application. By dynamically updating the DOM, developers
can deliver a seamless and interactive user experience.

Overall, through methods like 'getElementById()' or 'getElementByClass()', developers can


effectively manipulate the DOM to modify specific elements, while timely updates to the
DOM ensure the UI remains synchronized with the underlying application state.

How Virtual DOM speeds Up the Task


When new elements are added to an application, a virtual DOM is created, representing these
elements as a tree structure. Each element corresponds to a node within this virtual DOM.

In cases where an element's position changes, a new virtual DOM is generated. This fresh
virtual DOM is then compared to the previous version, identifying any differences or
modifications that have occurred.

By analyzing these discrepancies, the system determines the necessary adjustments to be


made in the actual DOM. These updates are precisely applied to ensure that the modified
elements are accurately rendered on the page, reflecting the intended changes in the user
interface.

In essence, the virtual DOM plays a vital role in managing the dynamic nature of web
applications. Through efficient comparison and targeted updates, the virtual DOM enables
seamless synchronization with the actual DOM, resulting in a visually updated and
harmonious user interface.

27
Awesome React.js

How Virtual DOM Works in React


React revolutionized the way we build user interfaces by introducing the concept of
components. In React, everything is observed as a component, be it a functional component
or a class component. These components possess a state, allowing them to manage and track
changes in their respective sections of the user interface.
Whenever a modification occurs in the JSX file, in simpler terms, when the state of a
component changes, React efficiently updates its virtual DOM tree. To achieve this, React
maintains two versions of the virtual DOM: the updated virtual DOM and a pre-updated
version of it. By comparing these two versions, React swiftly identifies the specific
components and elements that require modification.

Despite initially appearing to be an inefficient approach, the overhead of updating the virtual
DOM is surprisingly negligible. React's intelligent reconciliation process, known as "diffing,"
efficiently determines the differences between the current virtual DOM tree and its previous
version. Through this process, React precisely identifies what has changed, allowing it to
optimize updates to the actual DOM.

React utilizes batch updates to minimize unnecessary overhead when updating the actual
DOM. Instead of dispatching individual updates for each state change, React batches these
updates together and applies them collectively. By grouping changes, React reduces the
impact on performance and ensures that the actual DOM efficiently re-renders the user
interface.

The process of converting the identified changes into updates for the actual DOM is referred
to as ‘reconciliation’. This intelligent mechanism greatly enhances performance, making
React a beloved framework among developers. React's Virtual DOM, combined with its
reconciliation process, enables developers to create dynamic and responsive user interfaces
while maintaining optimal efficiency.
The concept of the Virtual DOM was introduced in React to optimize the performance and
speed of the Real DOM. Acting as a lightweight representation of the actual DOM, the
Virtual DOM operates by following a tree structure.

28
Awesome React.js
Instead of directly modifying the Real DOM whenever a change occurs, React updates the
Virtual DOM instead. Each element in the Virtual DOM tree corresponds to a node in the
Real DOM, accurately reflecting its structure. When new elements are added to the UI, nodes
are added to the Virtual DOM accordingly.
When changes happen, such as element repositioning, React generates a new Virtual DOM
tree. The Virtual DOM then intelligently calculates the minimal set of operations required to
synchronize the Real DOM with these changes. By precisely determining the necessary
modifications, the Virtual DOM avoids the costly process of re-rendering the entire Real
DOM.
This approach offers remarkable efficiency by minimizing the direct manipulation of the Real
DOM and selectively updating only the affected parts. As a result, the Virtual DOM
significantly enhances performance, enabling smoother and faster rendering of the user
interface.
Hence React's Virtual DOM optimizes the update process by serving as an intermediary layer
between the application and the Real DOM. By intelligently managing changes and reducing
unnecessary updates, the Virtual DOM enhances performance and delivers a more efficient
and responsive user experience.
Virtual DOM New Virtual DOM with Affected
Nodes

In React, the utilization of the Virtual DOM is central to its efficient rendering and updating
process. Let's explore how React leverages the Virtual DOM to deliver an enhanced user
experience:

29
Awesome React.js
 Each UI element is treated as a separate component, encapsulating its own state.
React employs the observable pattern, actively monitoring changes within these
component states.
 Whenever a modification is made to a component's state, React responds by updating
the Virtual DOM tree, while leaving the actual DOM untouched.
 Following the update, React performs a meticulous comparison between the current
version of the Virtual DOM and its previous iteration. This analysis allows React to
discern the specific objects that have been altered within the Virtual DOM.
 React then selectively replaces only the modified objects within the actual DOM,
resulting in minimal manipulation operations required. This intelligent process,
known as "diffing" or "reconciliation," ensures precise and efficient updates to the
rendered user interface.
 By leveraging the power of the Virtual DOM, React optimizes the update process,
avoiding unnecessary updates to the actual DOM. This approach significantly
enhances performance, delivering a smoother and more responsive user experience.
Thus, React's integration of the Virtual DOM enables it to efficiently track and manage
changes in component states. By selectively updating only the necessary portions of the
actual DOM, React minimizes overhead and improves rendering speed, making it a preferred
choice for building dynamic and high-performance user interfaces.

In the image, the dark blue circles are the nodes that have been changed. The state of these
components has changed. React computes the difference between the previous and current
version of the virtual DOM tree, and the entire parent sub-tree is re-rendered to show the UI
which is changed.

The updated tree is batch updated (that updates to the real DOM are sent in batches instead of
sending updates for each state change.) to the real DOM.

1.8 Comprehending JSX


JSX, an acronym for JavaScript XML, serves as a remarkable syntax extension of JavaScript.
It introduces a seamless and intuitive way to integrate HTML-like structures into JavaScript
code. With JSX, developers can elegantly blend the expressive power of JavaScript with the
familiar and structured nature of XML-based syntax.

30
Awesome React.js
The power of JSX lies in its ability to combine JavaScript logic and HTML-like markup
within a single file. This unique approach eliminates the need for separate template files,
providing a more cohesive and streamlined development experience.

By adopting JSX, developers gain the advantage of writing code that closely resembles
traditional HTML. This not only enhances readability but also enables easier visualization
and design of user interface components.

The seamless integration of JavaScript and JSX allows for the creation of highly dynamic and
interactive user interfaces. Developers can effortlessly leverage JavaScript's capabilities to
manipulate and update the JSX-rendered elements, resulting in flexible and responsive web
applications.

In essence, JSX unlocks the potential for harmonious coexistence between JavaScript and
HTML-like syntax. Its synergy empowers developers to craft visually appealing, functional,
and efficient web applications with ease and elegance.

Exploring JSX Further…


Salient Features of JSX

 JSX is an extension to the JavaScript language syntax.


 JSX is employed for writing XML-like code for elements and components.
 Similar to HTML, JSX tags possess a tag name, attributes and children.
 JSX while not necessary for writing React applications renders the code simpler and
elegant.
 Under the hood, JSX transpiles to pure JavaScript understood by all browsers.

Examples of JSX

The following functional component renders the message ‘Hello React’ in level 1 heading
using JSX.

hello.js

31
Awesome React.js
import React from 'react'
const Hello = () =>{
return(
<div>
<h1>Hello React</h1>
</div>
)
}
export default Hello

Embed the ‘Hello’ component as shown below:


App.js

import React from 'react';
import Hello from './components/hello';
class App extends React.Component {
render() {
return (
<div>
<Hello/>
</div>
);
}
}
export default App;

Switch to the folder containing React project and enter the following command:
npm start

On execution of the application, the following output is generated:

32
Awesome React.js

Using React Library


React.createElement() Method
React.createElement() method takes the following parameters:
 First parameters is the name of the element to be rendered.
 Second element is an object specifying the attribute name/value pair.
 Third element is children of first element.
The following example employs ‘React’ library in the place of JSX for rendering the message
in the browser.
hello.js

import React from 'react'
const Hello = () =>{
return(
React.createElement('div',null,'Hello React.js')
)
}
export default Hello

On execution of the application the following output is generated:

33
Awesome React.js
The following program presents a modified version of the above program which specifies the
second attribute for specifying the style.

hello.js

import React from 'react'
const Hello = () =>{
return(
React.createElement('div', { style: { color: 'red', fontSize:48 } },'Hello React.js')
)
}
export default Hello

On execution of the application the following output is generated:

To display the message in level1 heading using createElement() method modify the above
program as shown below:

hello.js

import React from 'react'
const Hello = () =>{
return(
React.createElement('div',null,'<h1>Hello React.js</h1>')
)
}
export default Hello

On execution of the application the following output is generated:

34
Awesome React.js

To check what is rendered in the browser, inspect the element by right-clicking on the
element and selecting ‘Inspect Element’ from the shortcut menu. The following output is
generated:

Hence the rendered element <h1> is not a DOM node it is just an inner text to <div> element.
The issue can be resolved using nested createElement() method as shown below:

To test modify the ‘hello.js’ program as shown below:

35
Awesome React.js

hello.js

import React from 'react'
const Hello = () =>{
return(
React.createElement('div', null,React.createElement('h1',null,'Hello React.js'))
)
}
export default Hello

On execution of the application the following output is generated. The message is displayed
in level 1 heading.

Each JSX element internally invokes React.createElement() method. Hence ‘React’ library
need to be imported while using JSX.

As the no. of elements increase the code becomes clumsy and unreadable, JSX keeps the
code simple, elegant and readable.

Difference Between HTML and JSX

HTML and JSX are both used for defining the structure and content of user interfaces, but
they have some key differences:

 Syntax: HTML uses angle brackets < > to enclose tags, while JSX uses a similar
syntax but integrates JavaScript expressions within curly braces { }.
 Tag Names: In HTML, tag names are case-insensitive, whereas in JSX, tag names
must be capitalized to be recognized as components. For example, in JSX, you would

36
Awesome React.js
write <Button /> for a component, whereas in HTML, <button></button> would
work.
 Attributes: HTML attributes are defined using HTML conventions, such as class for
specifying CSS classes and for for associating labels with form elements. In JSX,
these attributes are written using camelCase, such as className and htmlFor, to align
with JavaScript naming conventions.
 Expressions: In JSX, you can embed JavaScript expressions within curly braces { }.
This allows you to dynamically generate content and perform calculations within the
JSX code. In HTML, you typically need to rely on external JavaScript code to achieve
similar functionality.
 Inline Styling: HTML primarily uses CSS classes and inline styles defined with the
style attribute. In JSX, you can also use the style attribute to apply inline styles, but
the values are written as JavaScript objects rather than strings.
 Comments: In HTML, you can add comments using the <!-- --> syntax. In JSX,
comments are written inside curly braces as JavaScript-style comments, {/* */}.

It's important to note that JSX is not directly interpreted by the browser. It needs to be
transpiled into regular JavaScript using tools like Babel before it can be understood by
browsers.

Overall, JSX provides a way to write HTML-like syntax within JavaScript, allowing for more
expressive and dynamic UI components in React and other JavaScript frameworks.

1.9 Structure and Application Architecture of React.js Application


Components
At the core of a React.js application lie components, which offer modularity and facilitate
code reusability. Components in React play a pivotal role in creating modular and reusable
code. Each component represents a distinct user interface element within a React application,
enabling a structured and organized approach to development.

React offers two main types of components: class components and functional components.
Class components are considered stateful as they possess an internal state that can be
modified to trigger updates in the user interface. They provide a robust mechanism for
managing complex state logic and handling component-specific behaviour.

37
Awesome React.js
On the other hand, functional components are stateless and operate similarly to JavaScript
functions. These components receive a set of properties, known as props, as input. Props
allow data to be passed from parent components to child components, facilitating efficient
communication and customization.

To further empower functional components and enable them to handle state-related


operations, React introduced Hooks. Hooks serve as a bridge, granting functional components
access to state management features that were previously exclusive to class components.
With Hooks, developers can utilize functionalities like useState to create and manage states
within functional components, promoting code reusability and improving overall readability.

By incorporating Hooks, React not only enhances the flexibility and modularity of functional
components but also facilitates cleaner and more concise code. This allows developers to
build scalable and maintainable

The core essence of a React.js application lies in its composition of multiple components,
each with the unique responsibility of rendering reusable HTML code to the browser.
Through nesting these components, developers can construct intricate and sophisticated
graphical user interfaces (GUIs) with remarkable ease and flexibility.

One of the remarkable advantages of React.js is its efficient approach to updating the user
interface. Unlike the traditional approach of manipulating the real DOM directly, React.js
introduces the concept of a virtual DOM. This virtual representation of the DOM allows
React.js to optimize the rendering process by selectively updating only the components that
have been modified, rather than re-rendering the entire DOM tree. This optimization greatly
enhances performance, resulting in faster and more responsive applications.

By employing this efficient virtual DOM mechanism, React.js ensures that updates to the
user interface are handled in a streamlined and highly optimized manner. This approach
minimizes unnecessary re-rendering, saving valuable computational resources and enhancing
the overall efficiency of the application.

38
Awesome React.js
React.js harnesses the power of component-based architecture to construct complex and
reusable GUIs. By utilizing a virtual DOM, it optimizes the updating process, selectively
rendering only the modified components. This refined approach contributes to the creation of
polished applications that deliver exceptional user experiences while maintaining high
performance standards.

React.js Application Architecture


React.js, at its core, embraces a powerful component architecture that revolutionizes the
construction of graphical user interfaces (GUIs). By deconstructing the GUI into reusable
components, React.js empowers developers to craft elegant and sophisticated interfaces with
remarkable ease.

Each component in React.js represents a distinct, self-contained building block responsible


for rendering a specific portion of the GUI. These components embody modularity,
encapsulating their own logic, data, and rendering instructions. Through this modular design,
components can be effortlessly reused throughout the application, fostering code reusability,
maintainability, and efficiency.

The true beauty of React.js lies in its ability to compose these reusable components
seamlessly. By combining components together in a hierarchical structure, developers can
construct complex GUIs that effortlessly integrate smaller, specialized components into
cohesive and intuitive user interfaces. This composition allows for the creation of highly
customizable and scalable GUIs that can adapt and grow with the application's evolving
needs.

Furthermore, React.js leverages a virtual DOM, a lightweight representation of the actual


DOM, to optimize performance. This efficient rendering approach ensures that only the
modified components are updated, minimizing unnecessary re-rendering and significantly
improving efficiency.

With React.js' component architecture, developers are empowered to design and build
polished GUIs that captivate users. The modular nature of components, along with the

39
Awesome React.js
seamless composition capabilities, facilitates the creation of dynamic and visually stunning
applications, all while maintaining a streamlined and efficient development process.

Component Based Architecture

For example, a typical web application can be broken down into the following components:
● header
● footer
● main component
● top menu bar
● side menu bar

In the above example, each section represents a component which can be reused and
composed in different pages of a web application in a right manner to build the entire web
application.
Further, the components created in React.js can not only be used in other React.js
applications but also can be used in other frameworks such as Angular,js, Vue.js etc.
The React library stands tall on a robust foundation, boasting simplicity, flexibility, and
extensibility. Designed specifically for creating user interfaces within web applications, React
revolutionizes the traditional approach by leveraging the power of JavaScript in place of
HTML.

40
Awesome React.js
In a conventional web application, HTML is utilized for designing the user interface, while
JavaScript handles user interactions. React.js, however, introduces a paradigm shift by
minimizing the reliance on HTML and introducing JSX. JSX is a syntax extension for
JavaScript that allows developers to define UI elements using familiar and expressive
JavaScript syntax.

By embracing JSX, React enables developers to craft user interfaces using pure JavaScript.
This approach unlocks a new level of flexibility and reusability, as developers can seamlessly
integrate JavaScript logic with UI design. This cohesive integration of code eliminates the
need for separate HTML templates, streamlining the development process and promoting
code efficiency.

React's primary objective is to empower developers to build user interfaces using a unified
language, reducing cognitive load and enhancing productivity. By leveraging the full
capabilities of JavaScript, React fosters a seamless and intuitive development experience,
enabling developers to create polished user interfaces that are robust, dynamic, and highly
interactive.

React's solid foundation rests upon its simplicity, flexibility, and extensibility. By embracing
JavaScript and JSX, it enables developers to create user interfaces using pure JavaScript,
eliminating the need for separate HTML templates. This paradigm shift empowers developers
to build polished applications with greater ease and efficiency, all while leveraging the full
power of JavaScript.

Unlike many other user interface libraries, React takes a unique approach by avoiding the
introduction of a new template language. Instead, React introduces a set of elegantly simple
concepts that empower developers to design user interfaces using familiar JavaScript syntax.

Rather than separating logic and design within a template, React encourages the practice of
composing reusable components using JavaScript. This allows developers to seamlessly
integrate logic and UI design, fostering a cohesive and efficient development process.

41
Awesome React.js
By eliminating the need for a separate template language, React reduces complexity and
provides a more streamlined development experience. Developers can leverage their existing
knowledge of JavaScript to build user interfaces, making the learning curve smoother and
enabling faster development cycles.
React's simplicity lies in its core principles, which include the component-based architecture
and the virtual DOM. These concepts allow developers to break down the UI into reusable
components and efficiently update only the necessary parts of the UI, respectively. This
simplicity not only enhances code maintainability but also improves performance by
optimizing the rendering process.

React's distinctive approach lies in its avoidance of introducing a new template language.
Instead, it embraces simple yet powerful concepts that enable developers to seamlessly
integrate logic and design using JavaScript. This approach reduces complexity, fosters code
reusability, and promotes a more efficient and polished development experience.

The React library, renowned for its prowess in building user interfaces, remains focused on
its core functionality without imposing any specific patterns for complex application
development. Instead, developers are granted the freedom to choose the design pattern that
best suits their needs. However, the React community does advocate certain design patterns
that can enhance application development.

One such pattern highly recommended by the React community is the Flux pattern. Flux
promotes a unidirectional data flow, ensuring predictable state management and facilitating
better control over application behaviour. By adhering to this pattern, developers can
maintain a clear separation of concerns, making code organization and debugging more
manageable.

In addition to design patterns, the React library offers numerous concepts that empower
developers to write efficient and maintainable code. Higher-order components, context,
render props, and refs are among the powerful tools provided by React. These concepts
enable code reuse, facilitate communication between components, and empower developers
to implement advanced functionalities with ease.

42
Awesome React.js
Furthermore, React Hooks represents a developing concept in React, specifically aimed at
enhancing state management in larger projects. Hooks provide a more elegant and concise
way to handle state and lifecycle events in functional components, reducing the complexity
and enabling better code organization.
The high-level architecture of a React application, represented in the figure you mentioned,
encompasses various components, state management strategies, data flow patterns, and
interactions. This architecture emphasizes the modular nature of React applications, where
components can be nested, communicate with each other, and update the user interface
efficiently.

Thus, while the React library does not enforce specific design patterns, the community
recommends adopting patterns like Flux for improved application development. React also
provides a rich set of concepts and tools such as higher-order components, context, render
props, and hooks to enhance code quality and maintainability. The high-level architecture of
a React application encompasses components, state management, data flow patterns, and
interactions, fostering modular and efficient development practices.

43
Awesome React.js

● React app starts with a single root component.

● The core component is created by using one or more components.

● Each component can be nested with any other component at any level.

● Composition is one of the core concepts of the React library. Therefore, each
component is built by composing smaller components rather than inheriting one
component from another.

● Most of the components are user interface components.

● React apps may include third-party components for a specific purpose, such as
routing, animation, state management, etc.

44
Awesome React.js

Chapter 2
Demystifying React.js Life Cycle
2.1 React Component Life Cycle
In the realm of React.js, the life cycle of a component encompasses a sequence of events and
methods that occur from the moment the component is loaded into memory until it persists in
memory. These events and methods, collectively known as the component's life cycle, play a
vital role in its creation, rendering, updating, and eventual destruction.

45
Awesome React.js
React.js provides a well-defined set of life cycle methods that are invoked at different phases
of a component's existence. These methods allow developers to perform specific actions and
logic during key moments of the component's life cycle. By utilizing these methods,
developers can effectively manage and control the behaviour and appearance of components.

However, with the introduction of React Hooks, a more flexible and comprehensive approach
to managing component lifecycle and state has emerged. Hooks provide a paradigm shift,
enabling developers to utilize functions instead of class-based components, thus simplifying
and enhancing the management of component lifecycle and state.

With Hooks, developers can leverage functions such as useEffect, useMemo, and useState to
achieve granular control over component behaviour and state management. These Hooks can
be utilized to perform actions when the component is created, updated, or destroyed, as well
as to manage and manipulate component state with ease.

By adopting Hooks, developers can embrace a more streamlined and concise approach to
component lifecycle management, eliminating the need for class-based life cycle methods
and promoting code simplicity and readability.

React.js offers a comprehensive set of life cycle methods that govern the creation, rendering,
updating, and destruction of components. However, with the introduction of React Hooks,
developers can leverage functions to manage component lifecycle and state more effectively,
providing a more flexible and comprehensive solution for building robust and polished
applications.

The lifecycle of the component is divided into four phases listed below:
 Initial Phase

 Mounting Phase

 Updating Phase

 Unmounting Phase

46
Awesome React.js
2.2 Life Cycle Methods

Different cycle methods invoked during different phases are depicted in the following figure:

Each phase contains some lifecycle methods that are specific to the particular phase as
described below:

2.3 Initial Phase

47
Awesome React.js
During the initial phase of a component's life cycle, the component becomes part of the DOM
tree. This phase is pivotal as it initializes the component's Props and State by assigning them
default values. It's important to note that the initial phase occurs only once throughout the
component's life cycle.

Order of Execution of the methods in Class Component


 getDefaultProps()
It is used to assign the default value, if any for this.props object. It is a static method
invoked before the creation of the instance of the component or any props from the
parent is passed into it.

 getInitialState()
This method is deprecated after React version 16.3. Prior to React 16.3 it was used to
specify the default value of this.state. It was an instance method invoked after the
creation of the component but before rendering.

 Constructor

This is the first method called when an instance of a component is created. It is used
for initializing state, binding event handlers, and performing other setup tasks. It
receives the props as an argument. The super(props) call should be made within the
constructor to properly set up the component.

Order of Execution of the methods in Functional Component with


Hooks
When using a functional component with hooks, the order of execution is different as
compared to class component:

 getDefaultProps(): Not applicable. getDefaultProps() is specific to class


components and is not used in functional components with hooks.

 getInitialState(): Not applicable. getInitialState() is specific to class components


and is not used in functional components with hooks.

 constructor(): Not applicable. Constructors are not used in functional components


with hooks.

48
Awesome React.js
In functional components with hooks, the equivalent of initializing state is done using the
useState hook, like this:

import React, { useState } from 'react';

function MyComponent() {

const [state, setState] = useState(initialState);

// Rest of the component code

return (

// JSX markup

);

The useState hook initializes the state of the component and returns the current state value
and a function, setState to update the state. The initialState argument passed to useState sets
the initial value of the state.

Hence, during the initial phase of a component's life cycle, it becomes part of the DOM tree,
and Props and State are initialized with default values. The order of execution of methods
depends on whether the component is a class component or a functional component. This
phase lays the groundwork for the component's further life cycle events and methods.

2.4 Mounting Phase


In this phase, the instance of a component is created and inserted into the DOM tree. It
consists of the following life cycle methods.
 componentWillMount()
This is invoked immediately before a component gets rendered into the DOM tree for
the first time. In the case, when you call setState() inside this method, the component
will not re-render. It is deprecated in higher versions of React.
 getDerivedStateFromProps()
This method is invoked both during the initial rendering and the subsequent updates
of the component. It is a static life cycle method of the component class and enables
the updation of the state of the component based on the changes in It provides an
opportunity to update the state in response to changes in the incoming props before

49
Awesome React.js
rendering the component. However, it is recommended to use componentDidUpdate()
method in place of getDerivedStateFromProps() method.
The signature of the getDerivedStateFromProps() method is as follows:
static getDerivedStateFromProps(nextProps, prevState)
It takes the following two parameters:
● nextProps: The next set of props that the component will receive.
● prevState: The previous state of the component.

The method returns an object that represents the updated state, or null if there is no
update to the state. The returned state will be merged with the current state of the
component.
Here's an example usage of getDerivedStateFromProps() component life cycle method:
MyComponent.js

import React from 'react'
class MyComponent extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps.value)
console.log(prevState.value)
if (nextProps.value !== prevState.value) {
return {
value: nextProps.value
};
}
return null;
}

constructor(props) {
super(props);
this.state = {
value: props.valueu

render() {

50
Awesome React.js
return (
<div>
<h2>Value: {this.state.value}</h2>
</div>
);
}
}
export default MyComponent
In the example above, getDerivedStateFromProps() is used to compare the incoming value
prop with the previous state value. If they differ, the state is updated to reflect the new prop
value. The updated state is then used within the render() method to display the current value.

It's important to use getDerivedStateFromProps() judiciously, as it can make the component's


behaviour more complex and harder to reason about. In most cases, managing state and prop
changes can be effectively handled using other lifecycle methods or by using functional
components with hooks.
On execution of the above program, the following output is generated:

The values of current prop and previous state are logged to the console as shown in the
following figure:

51
Awesome React.js

Change the value of prop to ‘MBA’ as shown below:


<MyComponent value="MBA"/>

With this change, the following output is generated in the browser:

To check component rendering modify the above code as shown below. The console.log
statements are added to getDerivedStateFromProps() and render() methods.
MyComponent.js

import React from 'react'
class MyComponent extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
console.log("getDerivedStateFromProps invoked....")
console.log(nextProps.value)
console.log(prevState.value)

52
Awesome React.js
if (nextProps.value !== prevState.value) {
return {
value: nextProps.value
};
}
return null;
}
constructor(props) {
super(props);
this.state = {
value: props.value
};
}

render() {
console.log("render invoked")
return (
<div>
<h2>Value: {this.state.value}</h2>
</div>
);
}
}
export default MyComponent
On execution of the above application the following output is generated:

53
Awesome React.js
Each time the state changes the render() method is invoked.
 render()
This method is defined in each and every component and is responsible for generating
the JSX markup of the component. It is responsible for returning a single root HTML
node element. If you don't want to render anything, you can return a null or false
value.

 componentDidMount()
This is invoked immediately after a component is rendered and takes a position in the
DOM tree. Now, you can do any DOM querying operations asynchronously or
interact with external APIs.

MOUNTING LIFE CYCLE METHODS

MOUNTING LIFE CYCLE METHODS

54
Awesome React.js

MOUNTING LIFE CYCLE METHODS

MOUNTING LIFE CYCLE METHODS

55
Awesome React.js

The following program demonstrates mounting life cycle methods.


Mounting.js

import React, { Component } from 'react';
class Mounting extends Component {
constructor(props){
super(props)
this.state={
msg:"Hello"
}
console.log("Inside Constructor...")
}
static getDerivedStateFromProps(props,state){
console.log("Inside getDerivedStateFromProps method...")
return null
}
render() {
console.log("Inside render method...")
return (
<div>
<h1>Mounting Life Cycle Methods</h1>
</div>

56
Awesome React.js
);
}
componentDidMount(){
console.log("Inside componentDidMount method...")
}
}
export default Mounting;

App.js

import logo from './logo.svg';
import './App.css';
import Mounting from './components/Mounting'
function App() {
return (
<div className="App">
<Mounting/>
</div>
)
}
export default App;

On execution of the above program the following output is generated. As seen by the output
generated on execution of the application the order of execution of life cycle methods during
component mounting is:
 constructor
 getDerivedStateFromProps()
 render() and
 componentDidMount()

57
Awesome React.js

Mounting Child Components


The following program demonstrates the sequence in which the component life cycle
methods are invoked during mounting of parent and child components.
Mounting.js

import React, { Component } from 'react';
import MountingChild from './MountingChild';
class Mounting extends Component {
constructor(props){
super(props)
this.state={
msg:"Hello"
}
console.log("Inside Mounting Constructor...")
}
static getDerivedStateFromProps(props,state){
console.log("Inside Mounting getDerivedStateFromProps method...")
return null
}
render() {
console.log("Inside Mounting render method...")
return (
<div>

58
Awesome React.js
<div>
<h1>Mounting Life Cycle Methods</h1>
</div>
<MountingChild/>
</div>
);
}
componentDidMount(){
console.log("Inside Mounting componentDidMount method...")
}
}
export default Mounting;

MountingChild.js

import React, { Component } from 'react';
class MountingChild extends Component {
constructor(props){
super(props)
this.state={
msg:"Hello"
}
console.log("Inside MountingChild Constructor...")
}
static getDerivedStateFromProps(props,state){
console.log("Inside MountingChild getDerivedStateFromProps method...")
return null
}
render() {
console.log("Inside MountingChild render method...")
return (
<div>
<h2>Mounting Life Cycle Child Methods</h2>

59
Awesome React.js
</div>
)
}
componentDidMount(){
console.log("Inside MountingChild componentDidMount method...")
}
}
export default MountingChild;

On execution of the above program the following output is generated:

60
Awesome React.js
As seen by the output generated on execution of the above application when the parent
component contains the embedded child component, the order of execution of different life
cycle methods of parent and child components is as follows:
 constructor of parent component
 getDerivedStateFromProps() method of parent component
 render() method of of parent component
 constructor of child component
 getDerivedStateFromProps() method of child component
 render() method of of child component
 componentDidMount() of child component
 componentDidMount() of parent component

2.5 Updating Phase


In this phase, the component receives new Props and can also update its own State. It serves
as a crucial stage for handling user interactions and facilitating communication within the
component hierarchy. The primary objective of this phase is to ensure that the component
displays the most up-to-date version of its data and UI.

Unlike the initial and mounting phases, which occur only once, the updating phase can be
invoked multiple times throughout the life cycle of a component. This happens when there
are changes in Props or State, or when certain events trigger a re-render of the component.

During the updating phase, React performs a process called "diffing" to identify the changes
between the previous and new versions of the component's Props and State. Based on these
changes, React selectively updates only the necessary parts of the component and its children
in the virtual DOM.

The updating phase includes several methods that can be utilized in class components to
control the behaviour during this phase. These methods, such as shouldComponentUpdate,
componentDidUpdate, and getDerivedStateFromProps, provide developers with fine-grained
control over the updating process and enable optimization by preventing unnecessary re-
renders.

61
Awesome React.js
In functional components, the updating phase is managed using React Hooks, specifically the
useEffect and useState Hooks. These Hooks allow for handling side effects, responding to
prop changes, and managing component state in a concise and efficient manner.

In summary, the updating phase in the React component's life cycle is a vital stage where the
component receives new Props, updates its own State, and handles user interactions. Its
purpose is to ensure that the component reflects the most recent data and provides an updated
UI. Unlike the initial and mounting phases, the updating phase can occur multiple times, and
React provides methods and Hooks to manage and control the behaviour during this phase
effectively.

This phase involves of the following life cycle methods.


 componentWillRecieveProps(nextProps)
It is invoked when a component receives new props from its parent. For updating the
state in response to prop changes, this.props is compared with nextProps and state
transition is performed using this.setState() method. It is deprecated in higher
versions of React.

 shouldComponentUpdate(nextProps, nextState)

This method is employed to determine whether the component should re-render or


not. It is invoked when a component decides any changes/updation to the DOM. It
allows you to control the component's behaviour of updating itself. If this method
returns true, the component will update. Otherwise, the component will skip the
updating. By default it returns true.

 componentWillUpdate(nextProps, nextState)

It is invoked just before the component is updated and re-rendered. Here, you can't
change the component state by invoking this.setState() method. It will not be called,
if shouldComponentUpdate() returns false. It is deprecated in higher versions of
React.

 render()
It is invoked to examine this.props and this.state and to re-render the component
when there are state updates. If shouldComponentUpdate() returns false, the code

62
Awesome React.js
inside render() will be invoked again to ensure that the component displays itself
properly.

 componentDidUpdate(prevProps, prevState)

It is invoked immediately after the component has been re-rendered and updated
in the DOM tree. In this method, you can place any code which you want to
execute once the updating occurs based on new props and states. This method is
not invoked for the initial render.

UPDATING LIFE CYCLE METHODS

UPDATING LIFE CYCLE METHODS

63
Awesome React.js

UPDATING LIFE CYCLE METHODS

UPDATING LIFE CYCLE METHODS

64
Awesome React.js

UPDATING LIFE CYCLE METHODS

2.6 Unmounting Phase


The final phase of the React component lifecycle is known as the ‘unmounting phase’. This
phase occurs when a component instance is being removed and unmounted from the DOM
tree, signalling the end of its existence.

During the unmounting phase, React performs necessary cleanup tasks to ensure the proper
disposal of resources associated with the component. This could include cancelling network
requests, removing event listeners, or releasing any other resources acquired during the
component's lifecycle.

React provides a method in class components called componentWillUnmount, which is


invoked just before the component is unmounted from the DOM. Developers can utilize this

65
Awesome React.js
method to perform any required cleanup operations or finalize any ongoing processes.

In functional components, the unmounting phase can be managed using the useEffect Hook
by returning a cleanup function. This function will be executed when the component is
unmounted, allowing for resource cleanup or termination of any ongoing operations.

By properly handling the unmounting phase, developers can ensure the efficient release of
resources and prevent memory leaks or unnecessary computations. This phase plays a crucial
role in maintaining the overall performance and stability of the application.

The unmounting phase in the React component lifecycle occurs when a component instance
is being removed and unmounted from the DOM. It is the final stage of a component's
existence, and during this phase, React performs necessary cleanup tasks to release resources
associated with the component. By utilizing methods or Hooks provided by React, developers
can perform cleanup operations and ensure the proper disposal of resources, thereby
maintaining application performance and stability. This phase contains only one method
described below:
 componentWillUnmount()
This method is invoked immediately before a component is destroyed and unmounted
and removed permanently from DOM tree. It performs any necessary cleanup related
task such as invalidating timers, event listener, cancelling network requests, or
cleaning up DOM elements. If a component instance is unmounted, you cannot mount
it again.

66
Awesome React.js

Chapter 3
Unveiling the Symphony of React.js Concepts
3.1 Exploring React JSX
Within every React component, there is an embedded render() function that plays a crucial
role in generating the HTML output rendered in a browser. This function defines how the
component's UI should be displayed and is responsible for returning the JSX (JavaScript
XML) code that represents the component's structure and content.

JSX, an extension of React, allows developers to write JavaScript functions using a syntax
that resembles HTML. It provides a more intuitive and declarative way to define the structure
and behaviour of components. JSX code can include HTML-like tags, attributes, and
expressions, making it easier to express the desired UI elements and their dynamic behaviour.

However, JSX itself is not understood by JavaScript engines. It needs to be transformed into
standard JavaScript code before it can be executed. This transformation process is typically
handled by preprocessors like Babel, which convert JSX expressions into regular JavaScript
objects that can be understood and parsed by the JavaScript engine.

By using JSX, developers can write code that closely resembles the final HTML structure and
achieve a more concise and readable representation of the component's UI. This allows for
easier maintenance, better collaboration between developers, and improved code
organization.

The render() function in a React component is responsible for generating the HTML output
that is rendered in a browser. JSX, an extension of React, enables developers to write
JavaScript functions using a syntax similar to HTML. Preprocessors like Babel transform
JSX expressions into standard JavaScript objects that can be executed by JavaScript engines,
allowing for more intuitive and expressive component definitions. For example, the following
JSX

67
Awesome React.js
<div>Hello World </div> is converted into the following function call
React.createElement("div", null, "Hello World");

The createElement() method of ‘React’ object accepts the following three arguments:
● The first argument is the name of the element
● The second argument is the attribute of the element
● The third element is the content of the element

Why use JSX?


Through JSX React brings several advantages to web development, providing a polished and
efficient approach to building user interfaces. Here are some key benefits of React:

Enhanced Performance: React's code optimization techniques during the translation process
make it faster than regular JavaScript. It employs a virtual DOM that efficiently updates only
the modified components instead of re-rendering the entire HTML structure, resulting in
improved performance and a smoother user experience.

Consolidated Markup and Logic: Unlike traditional web applications where markup and
logic reside in separate HTML and JavaScript files, React combines them within components.
This consolidation simplifies code organization and promotes a more cohesive development
approach, allowing developers to easily manage and maintain both the visual representation
and the functionality of the application.

Type Safety: React offers a type-safe development environment, where most errors are
caught during compilation rather than at runtime. By utilizing tools like TypeScript or
PropTypes, developers can define and enforce strict type checks, enabling early detection of
potential errors and improving overall code reliability.

Streamlined Template Creation: React simplifies the creation of templates by utilizing JSX,
a syntax extension that allows developers to write HTML-like code directly within
JavaScript. This approach provides a more intuitive and concise way to define component
structures and their dynamic behaviour. JSX is then transformed into standard JavaScript
objects, facilitating template creation and maintenance.

68
Awesome React.js

Overall, React brings speed, consolidated markup and logic, type safety, and streamlined
template creation to web development. These advantages enhance performance, code
organization, error detection, and template creation, ultimately leading to more efficient and
polished applications.

Specifying JSX Attributes


Similar to HTML attributes JSX uses the attributes which are specified using the camel case
naming convention rather than traditional naming conventions.
We can also use our own custom attributes in JSX. For custom attributes, we need to use
data- prefix. In the below example, we have used a custom attribute data-institute as an
attribute for the <p> tag.
<p data-institute = "CSIBER">Institute Located in Kolhapur</p>

JSX Comments
JSX allows us to use comments that begin with /* and ends with */ and wrapping them in
curly braces {} just like in the case of JSX expressions.

JSX Styling
React strongly recommends the use of inline styles to apply styling to elements. When setting
inline styles in React, it is important to follow the camel case syntax, where the first word is
in lowercase and the first letter of each subsequent word is capitalized. React also
conveniently handles the addition of the 'px' unit after numeric values for specific elements.
Here's an example that demonstrates the usage of inline styles in a React element:
import React from 'react';
const MyComponent = () => {
const divStyle = {
backgroundColor: 'blue',
color: 'white',
fontSize: '20px',
padding: '10px',
};

69
Awesome React.js
return (
<div style={divStyle}>
This is a styled div element.
</div>
);
};
export default MyComponent;

JSX Expressions
JSX expressions are specified using curly braces. The following example demonstrates using
inline styles in React.js applications.
Insert the following code in ‘App.js’ file.
App.js

import './App.css';
function App() {
return (
<div className="App">
<p style={{fontSize:72}}>Hello JSX</p>
</div>
);
}
export default App;

On execution of the above application the following output is generated:

70
Awesome React.js
Alternatively, the CSS rules can be stored in a variable and assigned to the ‘style’ attribute of
HTML element as demonstrated in the following example:

App.js

import React, { Component } from 'react';
class App extends Component{
render(){
var myStyle = {
fontSize: 72,
color: '#0000ff'
}
return (
<div>
<h1 style = {myStyle}>Hello JSX</h1>
</div>
);
}
}
export default App;

On execution of the above application the following output is generated:

Note: JSX does not allow use of if..else statements. However, the ternary expressions can be
used inside JSX as demonstrated in the following example.

Use of ternary expression in JSX is demonstrated in the following program:

71
Awesome React.js

App.js

import React, { Component } from 'react';
class App extends Component{
render(){
var myStyle = {
fontSize: 72,
color: '#0000ff'
}
var errorStyle = {
fontSize: 72,
color: '#ff0000'
}
let error = false
let stylename = error?errorStyle:myStyle
return (
<div>
<h1 style = {stylename}>Hello JSX</h1>
</div>
);
}
}
export default App;
On execution of the above application the following output is generated. The style applied to
the <H1> element depends on the value of the boolean variable ‘error’. If it is true
‘errorStyle’ is applied else ‘errorStyle’ is applied.

72
Awesome React.js

Replace the statement


let error = false with the following one and reexecute the application.
let error = true
On execution of the application now, the following output is generated:

Note: Only one parent element is allowed in JSX.


The following code renders two <div> element which will generate an error as shown in the
following figure:
App.js

import './App.css';
function App() {
return (
<div>
<font color='red'><p style={{fontSize:36}}>Hello React.js</p></font>
</div>
<div>
<font color='green'></font><p style={{fontSize:36}}>Hello JSX</p></font>
</div>
);
}

73
Awesome React.js
export default App;
On execution of the above application the following error message is generated:

To fix the error wrap the two <div> elements into a single <div> element as shown in the
following code snippet.
App.js

import './App.css';
function App() {
return (
<div>
<div>
<font color='red'><p style={{fontSize:36}}>Hello React.js</p></font>
</div>
<div>
<font color='green'><p style={{fontSize:36}}>Hello JSX</p></font>
</div>
</div>
);
}
export default App;
On execution of the program the following output is generated:

3.2 Exploring the First React.js Application


For developing the first React.js application follow the steps enumerated below:
● Switch to C:\ drive and create a folder with the name ‘react’ in it.

74
Awesome React.js
● Open the folder in VSCode editor.

The simplest way to create a new React,js application is using a command-line tool ‘Create
React App’ which enables creating and running React.js applications without involving any
explicit configuration. The entire React.js project is created on the execution of a single
command.
In the integrated terminal of VSCode switch to ‘react’ folder created above and enter the
following command:
npx create-react-app <react_project_name>
npx create-react-app hello-world
On execution of the above command, the following output is generated:

On the successful execution of above command, the folder with the name ‘hello-world’ is
created with the following structure:

75
Awesome React.js

To run the React.js application created above, switch to ‘hello-world’ folder and enter the
command
npm start
The command will start development server and open the browser on localhost port 3000
with the ‘hello world’ application up and running as shown in the following figures:

76
Awesome React.js

Configuring the React.js Application


For configuring the React.js application created above, back in VSCode, expand ‘hello-
world’ folder and then ‘src’ folder. Open ‘App.js’ file in the editor.

Change the text to ‘Hello Welcome to First React.js Application’ as shown in the above
figure:

77
Awesome React.js
On saving the changes in VSCode editor, the application will automatically recompile and
browser will refresh automatically to reflect the changes as shown below:

Alternate approaches for creating React App using create-react-app


command.
Using npx Command
npx is NPM package runner which is automatically installed when node is installed.
An alternate method is installing ‘create-react-app’ package globally using NPM and then
using the package to generate projects.
The command for creating React.js application using ‘npx’ command is shown below:
npx create-react-app <project_name>

Using npm Command


The command for creating React.js application using ‘npx’ command is shown below:
npm install create-react-app -g
create react-app <project_name>

3.3 React.js Application Folder Structure


When executing the above command, a React project is typically created with a predefined
directory structure. Here's a brief introduction to the different files and folders commonly
found in the root directory of a React project:

78
Awesome React.js
src: This folder contains the main source code of your React application. It usually includes
JavaScript files, components, stylesheets, and other related assets.

Content of ‘src’ Folder


The default content of ‘src’ folder is shown in the following figure. This is the folder the
developer will be working with most of the time during development.

The App.js file is responsible for rendering the output on the browser.

public: The public folder contains static files that will be served as-is to the client without any
processing. It usually includes the index.html file, which acts as the entry point for your
React application.

node_modules: This folder is created when you install external dependencies for your React
project using package managers like npm (Node Package Manager) or Yarn. It stores all the
installed packages and their dependencies.

79
Awesome React.js

package.json: This file is the heart of your React project. It includes metadata about your
project, such as the project name, version, dependencies, scripts, and more. It also serves as a
configuration file for npm or Yarn.

80
Awesome React.js

package-lock.json or yarn.lock: These files lock the exact versions of the installed packages
and their dependencies. They ensure that the same versions are used across different
development environments, providing consistency and reproducibility.

.gitignore: This file specifies which files and folders should be ignored by version control
systems like Git. It typically includes files such as build artifacts, logs, and dependencies
managed by package managers.

README.md: This file serves as the documentation for your project. It usually includes
information about the project's purpose, installation instructions, usage guidelines, and any
other relevant details.

.babelrc or babel.config.js: If your project uses Babel to transpile modern JavaScript syntax
to a compatible version, you may have a configuration file that specifies the Babel presets,
plugins, and other settings.

81
Awesome React.js
webpack.config.js or react-scripts: If your project utilizes Webpack as the bundler, you
might have a configuration file that defines how the source code, stylesheets, and assets are
processed, bundled, and optimized.

These are some of the common files and folders you may encounter in the root directory of a
React project. Each file and folder plays a specific role in organizing, configuring, and
building your React application.

manifest.json
It is used for designing progressive web apps.
A progressive web application, or progressive web app, is a type of application software
delivered through the web, built using common web technologies including HTML, CSS,
JavaScript, and WebAssembly. It is intended to work on any platform with a standards-
compliant browser, including desktop and mobile devices

Favicon.ico
It is the icon which is displayed in the browser window when the React.js application is
executed.

index.html File
It is the only HTML file present in the Single Page Application (SPA). The <body> tag of
HTML file contains the <div> tag with the ‘id’ attribute set to ‘root’ as shown in the
following figure. This <div> tag is responsible for UI. React will mount the application by
default on the ‘root’ node.

82
Awesome React.js

3.4 React.js Application Execution Steps


The starting point of React.js application is ‘index.js’ whose content is shown below:

The 'index.js' file serves as a crucial entry point for a React application. It initiates the process
by importing necessary modules such as 'React', 'ReactDOM', and the 'App' module. In this
file, the root component is explicitly defined, which in this case refers to the 'App' component
specified in the separate 'App.js' file.

83
Awesome React.js
The primary responsibility of 'index.js' is to render the root component in the web browser.
React takes control of the Document Object Model (DOM) manipulation, which involves
managing and updating the web page's elements dynamically. The specific DOM element
that acts as the container for the application is a <div> element identified by the 'root' id. This
<div> element is declared within the 'index.html' file.
To summarize, 'index.js' file facilitates the creation of the root component, associating it with
the <div> element defined in the 'index.html' file. It then proceeds to render the 'App'
component, enabling the React framework to take over the DOM manipulation.
Consequently, the only DOM element of importance is the <div> element with the 'root' id,
which acts as the container for the React application within the web page.

App.js File
The 'App.js' file plays a pivotal role in generating the HTML content that is ultimately
displayed in the web browser window. It defines the structure and layout of the view
presented to the user. The file typically encompasses components, logic, and styling required
to create a cohesive user interface.

Within the 'App.js' file, various components and their corresponding functionality are
defined. These components are responsible for rendering specific parts of the user interface,
such as headers, navigation menus, content sections, forms, or any other elements required
for the application.

By composing these components together, the 'App.js' file creates a cohesive and interactive
view that is presented to the user. This view may consist of text, images, buttons, input fields,
or any other visual elements necessary for the application's purpose.

Thus 'App.js' file is instrumental in defining the structure and content of the HTML view
displayed in the web browser. It encapsulates components and their associated logic, ensuring
a visually appealing and functional user interface.

84
Awesome React.js

Working of React.js Application


 The React.js application starts with the 'index.html' file, which serves as the initial
entry point. When the 'npm start' command is issued, the application loads the
'index.html' file, which contains the root DOM node.
 The control then moves to the 'index.js' file, where the ReactDOM component comes
into play. It uses the 'ReactDOM.render()' method to render the root component,
which is defined in the 'App.js' file, onto the root DOM node.
 Inside the 'App.js' file, the App component holds the necessary HTML content that
will be rendered in the browser window. This component defines the structure and
layout of the user interface.
 The App component acts as the root component of the component hierarchy and is
responsible for rendering all other components within the application. It serves as the
central point for managing and coordinating the various components.
 The power of component reusability comes into play, allowing the same components
to be utilized across multiple user interfaces. This reusability is particularly useful for

85
Awesome React.js
elements such as navigation bars, where the same component can be used on different
pages or screens.
 Components can also be nested within one another, enabling the creation of complex
component hierarchies. This nesting allows for the composition of smaller, reusable
components into larger and more intricate ones.
 Additionally, components offer customization capabilities. The same component can
be rendered with different properties, allowing for the display of varying information
or visual styles. This flexibility enhances the versatility and adaptability of React
components.
To consolidate, the React.js application follows a sequence of steps, starting from the
'index.html' file, moving to the 'index.js' file for rendering the root component, and eventually
displaying the HTML content defined in the 'App.js' file. Components play a crucial role in
creating reusable, nested, and customizable user interfaces, providing an efficient and flexible
development approach.

3.5 React DOM Package


React DOM is a package provided by React that serves as the bridge between React
components and the Document Object Model (DOM). It enables the rendering of React
components into the browser DOM.

86
Awesome React.js
 Create a folder with the name ‘test_react’ in C:\ folder and open it in VSCode.
 Navigate to your project directory in the terminal and install the required
dependencies by running the following commands:
npm install react react-dom webpack webpack-cli babel-loader @babel/core
@babel/preset-react --save-dev

 Create a new file called webpack.config.js in the root of your project directory. Add
the following code to the file:
webpack.config.js

const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react'],
},
},
},
],
},

87
Awesome React.js
};
 Create a new file called index.js in the root of your project directory. Add the
following code to the file:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return React.createElement(
'div',
null,
React.createElement('h1', null, 'Hello, React!')
);
}
ReactDOM.render(React.createElement(App), document.getElementById('root'));

 Create a new file called index.html in the root of your project directory. Add the
following code to the file:
<!DOCTYPE html>
<html>
<head>
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script src="dist/bundle.js"></script>
</body>
</html>

 Build your React application by running the following command:


npx webpack --mode development

88
Awesome React.js

On successful compilation ‘dist’ folder is created in the project folder which contains the
artifact ‘bundle.js’.

To execute the application start a local development server by issuing the following
command:
npx serve

89
Awesome React.js
Open your web browser and navigate to the URL provided by the server. You should see the
‘Hello, React!’ message rendered on the web page.

Using JSX
The above program can be re-written using JSX as shown below:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1>Hello, React!</h1>
</div>
);
}

Displaying the Heading in Red Color


To display the heading in red color modify ‘index.js’ file as shown below:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return React.createElement(
'div',
null,

90
Awesome React.js
React.createElement('h1', { style: { color: 'red' } }, 'Hello, React!')
);
}
ReactDOM.render(React.createElement(App), document.getElementById('root'));

On execution of the above application the following output is generated:

Using JSX
The above program can be re-written using JSX as shown below:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1 style={{ color: 'red' }}>Hello, React!</h1>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));

Note: Each time the changes are made to the file build the project using the following
command
npx webpack --mode development

91
Awesome React.js
Creating Nested Elements Using ReactDOM
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return React.createElement(
'div',
null,
React.createElement(
'h1',
{ style: { color: 'red' } },
'Hello, ',
React.createElement(
'font',
{ color: 'blue' },
'React!'
)
)
);
}
ReactDOM.render(React.createElement(App), document.getElementById('root'));

Using JSX
The above program can be re-written using JSX as shown below:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1 style={{ color: 'red' }}>

92
Awesome React.js
Hello, <font color="blue">React!</font>
</h1>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));

Creating a Nested List


To create a nested list using ReactDOM package modify ‘index.js’ package as shown below:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return React.createElement(
'div',
null,
React.createElement(
'ul',
null,
React.createElement('li', null, 'Item 1'),
React.createElement('li', null, 'Item 2'),
React.createElement(
'li',
null,
'Item 3',
React.createElement(
'ul',
null,
React.createElement('li', null, 'Nested Item 1'),
React.createElement('li', null, 'Nested Item 2'),
React.createElement('li', null, 'Nested Item 3')
)

93
Awesome React.js
),
React.createElement('li', null, 'Item 4')
)
);
}
ReactDOM.render(React.createElement(App), document.getElementById('root'));

On execution of the above application the following output is generated:

Using JSX
The above program can be re-written using JSX as shown below:
index.js

import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>
Item 3
<ul>
<li>Nested Item 1</li>
<li>Nested Item 2</li>

94
Awesome React.js
<li>Nested Item 3</li>
</ul>
</li>
<li>Item 4</li>
</ul>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));

Here is an example of how to use React DOM in a React application:


 Install React DOM: Ensure that you have React and React DOM installed in your
project. You can use npm or yarn to install them.
npm install react react-dom
 Import necessary modules: In your JavaScript file (e.g., 'index.js'), import the required
modules.
import React from 'react';
import ReactDOM from 'react-dom';
 Create a root component: Define your root component (e.g., 'App') that represents the
main structure of your application.
function App() {
// Your component logic and JSX code here
return (
<div>
<h1>Hello, React!</h1>
</div>
);
}
 Render the root component: Use the ReactDOM.render() method to render the root
component onto the DOM. Specify the component and the target DOM element
where it should be rendered (usually a <div> element with a specific id).
ReactDOM.render(<App />, document.getElementById('root'));

95
Awesome React.js
 HTML structure in 'index.html': In your 'index.html' file, make sure to have a target
DOM element with the id specified as 'root'. This is where your React component will
be rendered.
<!DOCTYPE html>
<html>
<head>
<!-- Your head content here -->
</head>
<body>
<div id="root"></div>
<!-- Your other HTML content here -->
<script src="index.js"></script>
</body>
</html>
 Start the application: Run your React application using a development server (e.g.,
'npm start') to see your component rendered in the browser.

React DOM takes care of efficiently updating the DOM when changes occur in your React
components. It provides a seamless way to integrate React's virtual DOM with the actual
browser DOM, ensuring efficient and optimized rendering of your application.

Using React.createElement() allows you to create React elements dynamically and


programmatically, which can be useful in certain situations where JSX syntax is not available
or desired. However, JSX is generally preferred due to its readability and ease of use in
defining React components.

Here's an example of how to use React.createElement() to create a simple React component:


import React from 'react';
import ReactDOM from 'react-dom';
// Create a functional component using React.createElement()
const Greeting = () => {
return React.createElement('h1', null, 'Hello, React!');
};

96
Awesome React.js
// Render the component using ReactDOM.render()
ReactDOM.render(React.createElement(Greeting), document.getElementById('root'));

In this example, we define a functional component called Greeting using


React.createElement(). The Greeting component simply renders an <h1> element with the
text "Hello, React!".

We then use ReactDOM.render() to render the Greeting component onto the DOM,
specifying the component element and the target DOM element with the id of 'root'.

Make sure to have an 'index.html' file with a <div> element with the id of 'root' to serve as
the target for rendering the React component as shown in the following code snippet:
<!DOCTYPE html>
<html>
<head>
<!-- Your head content here -->
</head>
<body>
<div id="root"></div>
<!-- Your other HTML content here -->
<script src="index.js"></script>
</body>
</html>

When you run the React application, the Greeting component will be rendered as an <h1>
element with the text ‘Hello, React!’ inside the target <div> element in the browser.

Note that while React.createElement() provides a way to create React components without
JSX, JSX syntax is generally more commonly used and recommended for its simplicity and
readability.

Creating Nested Elements


Here's an example of how to use React.createElement() to create nested React elements:

97
Awesome React.js
import React from 'react';
import ReactDOM from 'react-dom';
// Create a functional component with nested elements using React.createElement()
const App = () => {
return React.createElement('div', null,
React.createElement('h1', null, 'Nested Elements Example'),
React.createElement('p', null, 'This is a paragraph.'),
React.createElement('ul', null,
React.createElement('li', null, 'Item 1'),
React.createElement('li', null, 'Item 2'),
React.createElement('li', null, 'Item 3')
)
);
};
// Render the component using ReactDOM.render()
ReactDOM.render(React.createElement(App), document.getElementById('root'));
In this example, we create a functional component called App using React.createElement().
The App component contains a <div> element as its root, which encloses several nested
elements.

Inside the <div> element, we have an <h1> element with the text ‘Nested Elements
Example’, a <p> element with the text ‘This is a paragraph.’, and a <ul> element that
contains three <li> elements with the text ‘Item 1’, ‘Item 2’, and ‘Item 3’.

We use React.createElement() recursively to create the nested structure, ensuring that each
child element is passed as an argument to its parent element's React.createElement() call.

Finally, we render the App component using ReactDOM.render(), specifying the component
element and the target DOM element with the id of 'root'.

When you run the React application, the nested elements defined in the App component will
be rendered accordingly in the browser, resulting in the structured HTML representation as
defined in the React.createElement() calls.

98
Awesome React.js
Rewriting the Code Using JSX
he same example can be written using JSX syntax, which is generally more readable and
widely used. Here's how the nested elements example can be written using JSX:

import React from 'react';


import ReactDOM from 'react-dom';
// Create a functional component with nested elements using JSX
const App = () => {
return (
<div>
<h1>Nested Elements Example</h1>
<p>This is a paragraph.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
);
};
// Render the component using ReactDOM.render()
ReactDOM.render(<App />, document.getElementById('root'));

In this JSX version, we define the App component using the familiar JSX syntax. Within the
return statement of the component, we can directly write the desired nested HTML structure
as JSX code.

The nested elements are expressed using HTML-like tags and nested indentation, which
enhances readability and makes it easier to visualize the structure of the component.
Finally, we use ReactDOM.render() to render the App component, wrapping it with the JSX
syntax <App />, and specifying the target DOM element with the id of 'root'.

99
Awesome React.js
When you run the React application with JSX, the nested elements defined in the App
component will be rendered as specified, providing the same structured HTML representation
as in the JSX code.

React.createElement
Used to create React elements. It expects three parameters -
 Element tag

 Element attributes as object

 Element content - It can contain nested React elements 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,
By analyzing the application, we can visualize the workflow of the React application, as
shown in the following figure:

100
Awesome React.js
In a React application, the ReactDOM.render method serves as a vital component in the
rendering process of the user interface. It acts as the conduit that connects the React
components, typically written in JSX or React Element format, to the specific container
where the UI will be displayed.

When the ReactDOM.render method is invoked, it triggers the transformation of the


component-based structure defined by JSX or React Element code into tangible HTML
elements that can be visually rendered on a web page. This method requires two crucial
parameters: the React component that represents the UI, and the target container element
where the UI will be mounted.

By employing ReactDOM.render, the React application efficiently manages updates to the


user interface, utilizing a virtual DOM mechanism that optimizes rendering performance. It
intelligently compares the previous and current states of the UI components, applying only
the necessary changes to the real DOM. This approach ensures a highly responsive and
interactive user experience.

Through the effective utilization of ReactDOM.render, React empowers developers to create


dynamic and captivating web applications. It seamlessly bridges the gap between the
declarative component structure, as defined in JSX or React Element, and the actual
rendering of the UI within the specified container element.

ReactDOM.render processes JSX or React Elements and emits virtual DOM. The virtual
DOM will be merged and rendered in the container.

The different steps are summarized below:


When JSX is used in a React component, it is transpiled into React elements before being
rendered into the DOM. This transpilation process typically occurs during the build process,
using a tool like Babel. Here's a simplified overview of how JSX is converted into React
elements:
 JSX Syntax
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within
JavaScript. JSX syntax resembles HTML but also incorporates JavaScript expressions and
components.

101
Awesome React.js
 Babel Transformation
During the build process, a tool like Babel is used to transform JSX code into regular
JavaScript code. Babel processes the JSX syntax and transpiles it into a series of function
calls.
 React.createElement()
The transpiled JSX code is transformed into a call to the React.createElement() method.
React.createElement() is a factory function provided by React that creates React elements.
Element Creation:
The React.createElement() function takes three arguments:
 Type: The type of the element, such as a string for HTML tags ('div', 'span') or a
component function/class.
 Props: An object containing the properties and attributes to be passed to the element.
 Children: The child elements or text content of the element.
The React.createElement() function creates a plain JavaScript object, known as a React
element, representing the JSX code.
 Virtual DOM Representation
The created React element is a lightweight representation of the corresponding component or
DOM element. React uses these elements to construct and manage a virtual representation of
the DOM, known as the Virtual DOM.
 Render and Update
The React elements are then used by React to efficiently render and update the actual DOM.
React performs a process called reconciliation, where it compares the previous and current
Virtual DOMs to determine the minimum number of changes needed to update the actual
DOM.
 DOM Update
React applies the necessary updates to the actual DOM based on the changes identified
during reconciliation. Only the modified parts of the DOM are updated, resulting in
optimized rendering performance.

This process allows developers to write JSX code, which is more expressive and readable
than creating React elements manually. JSX simplifies the creation of React components and
closely resembles the structure of the resulting HTML elements in the rendered output.

102
Awesome React.js
React DOM Library

It is used for building the actual user interface part of React.js application.

Declarative Paradigm

React.js employs declarative paradigm which implies the user only need to specify what is
required to be done and not how. In contrast to this in imperative paradigm, the user needs to
specify how a particular task is to be performed by clearly specifying the sequence and flow
of actions. It contains discrete instructions about performing a particular task. You need to
tell React.js how GUI should look like and React.js will build it for you hiding the internal
details from the end user. React.js will automatically handle rendering of GUI components
and updating the part of the UI as required. DOM updates are handled gracefully in React.js.

3.6 Setting Up of Development Environment for React.js


Pre-requisite for React.js
1. Node.js and NPM

2. React and React DOM

3. Webpack

4. Babel

Installing Webpack
Webpack serves as a versatile and essential tool for module packaging, automating
development and production pipelines. It empowers developers by offering webpack-dev-
server for streamlined development, webpack for generating optimized production builds, and
webpack CLI for executing various webpack commands.

During development, webpack-dev-server proves invaluable with its live reloading and hot
module replacement features. This enables developers to experience real-time changes and
improvements to their code without manually refreshing the browser. It facilitates a smooth
and efficient development experience.

103
Awesome React.js
For production builds, webpack takes the stage, orchestrating the compilation and
optimization of modules into a unified bundle. This single file incorporates all the necessary
dependencies, assets, and scripts, ensuring efficient delivery to end-users. By intelligently
bundling resources, webpack optimizes performance and reduces load times, resulting in a
seamless user experience.

To install webpack, developers can execute the following command:


npm install webpack --save-dev

This command, executed within the project directory, ensures webpack is installed as a
development dependency, seamlessly integrating it into the build process. With webpack in
place, developers gain enhanced control over module management and bundling, enabling
them to create performant and scalable web applications.
You can also use the above command separately which can be shown as below.
npm install webpack --save
npm install webpack-dev-server --save
npm install webpack-cli --save

Installing Babel

Babel, an essential JavaScript compiler and transpiler, plays a pivotal role in transforming
source code to various compatible versions. It serves as a powerful tool for converting React
JSX and ES6 code into ES5 JavaScript, ensuring broad browser compatibility.

To handle JSX file types seamlessly, the integration of babel-loader becomes necessary. This
loader seamlessly incorporates Babel into webpack, enabling smooth compilation of JSX files
within the build process.

To enhance the development experience, babel-preset-react proves invaluable. By using this


preset, your browser automatically updates whenever changes occur in the code, without
losing the current state of your application. This feature enables a seamless and efficient
development workflow, promoting productivity and user satisfaction.

104
Awesome React.js
Additionally, to leverage the latest ECMAScript features, babel-preset-env becomes essential.
This preset empowers developers to write modern, clean code while maintaining
compatibility with various browser versions. It ensures that your code remains optimized and
efficient across different environments.

To install Babel and its necessary dependencies, you can employ the following command:
npm install babel-loader @babel/preset-react @babel/preset-env --save-dev

Executing this command within your project directory ensures the installation of the required
packages, seamlessly integrating Babel into your webpack setup. With Babel in place, you
can harness the full potential of modern JavaScript syntax and React JSX while guaranteeing
compatibility across browsers.
npm install babel-core babel-loader babel-preset-env babel-preset-react babel-webpack-
plugin --save-dev

Generating the Production Bundle


To generate the bundle for your application, you can utilize the ‘build’ command in the
command prompt. This command triggers the bundling process, where imported files are
combined into a single file known as a ‘bundle’ By including this bundle on a webpage, your
entire application can be loaded efficiently in one go.

Here's an example of the ‘build’ command you can run in the command prompt:
npm run build

Executing this command initiates the build process, during which webpack performs
transformations, optimizations, and bundling operations on your application's source code.
The resulting bundle file encompasses all the necessary dependencies, assets, and scripts
required for your app to function seamlessly.

By running the ‘build’ command, you ensure that your application is packaged and prepared
for deployment. The generated bundle is a consolidated file that can be effortlessly integrated
into your webpage, enabling users to experience a smooth and responsive application.

105
Awesome React.js
Remember to run the build command in the appropriate directory where your project resides.
Upon successful completion of the build process, you will have a fully generated bundle
ready for deployment, allowing users to effortlessly access and interact with your application.

npm run build

This command will generate the bundle in the current folder(in which your app belongs)
For developing the applications using React.js, Node.js is required to be installed on the
target machine. You can use any editor of your choice (preferably VSCode) for building
applications in React.js.

To check whether Node.js is available on the target machine, open a command window and
enter the following command.
node -v

If node is installed on the target machine, the version of Node.js is displayed as shown in the
following figure:

3.7 Developing a First React.js Application Using create-react-app


(CRA Tool)
Advantages Offered by create-react-app
Creating a new React project can initially seem complex due to the multitude of build tools
involved. However, the introduction of the Create React App CLI tool has revolutionized the
process, making it significantly simpler and more accessible.
By installing the Create React App package using NPM and following a few straightforward
commands, you can swiftly set up a new React project. This eliminates the need for manual
configuration and alleviates the burden of managing dependencies like Webpack and Babel.
With Create React App, developers can instantly dive into writing React code, focusing
solely on their application's logic and design.
Create React App goes beyond just setting up the development environment. It provides an
exceptional developer experience by automating optimizations and best practices for
production-ready applications. This includes efficient bundling, code minification, and other
performance enhancements, allowing your React app to shine when deployed.

106
Awesome React.js
The beauty of Create React App lies in its ability to abstract away the complexities of build
tools, enabling both beginners and experienced developers to start coding without the initial
hurdles. It empowers developers to concentrate on what matters most—building high-quality
React applications—while enjoying a streamlined and optimized development process.
In essence, Create React App serves as a remarkable tool, simplifying the creation and
maintenance of React projects. With its seamless setup, outstanding developer experience,
and production-ready optimizations, Create React App is a game-changer in the React
ecosystem.

Pre-requisites for create-react-app


1. Node version >= 8.10

2. NPM version >= 5.6

For developing the first React.js application follow the steps enumerated below:
● Switch to C:\ drive and create a folder with the name ‘react’ in it.
● Open the folder in VSCode editor.
The simplest way to create a new React,js application is using a command-line tool ‘Create
React App’ which enables creating and running React.js application without involving any
explicit configuration. The entire React.js project is created on the execution of a single
command.

107
Awesome React.js
In the integrated terminal of VSCode switch to ‘react’ folder created above and enter the
following command:
npx create-react-app <react_project_name>
npx create-react-app hello-world
On execution of the above command, the following output is generated:

On the successful execution of above command, the folder with the name ‘hello-world’ is
created with the following structure:

108
Awesome React.js
To run the React.js application created above, switch to ‘hello-world’ folder and enter the
command
npm start
The command will start development server and open the browser on localhost port 3000
with the ‘hello world’ application up and running as shown in the following figures:

Configuring the React.js Application


For configuring the React.js application created above, back in VSCode, expand ‘hello-
world’ folder and then ‘src’ folder. Open ‘App.js’ file in the editor.

109
Awesome React.js

Change the text to ‘Hello Welcome to First React.js Application’ as shown in the above
figure:
On saving the changes in VSCode editor, the application will automatically recompile and
browser will refresh automatically to reflect the changes as shown below:

110
Awesome React.js
Alternate approaches for creating React App using create-react-app
command.
Using npx Command
We can combine the above two steps in a single command using npx. The ‘npx’ is a package
runner tool which comes with ‘npm’ 5.2 and higher version.
npx is NPM package runner which is automatically installed when node is installed.

An alternate method is installing ‘create-react-app’ package globally using NPM and then
using the package to generate projects.
The command for creating React.js application using ‘npx’ command is shown below:
npx create-react-app <project_name>

Using npm Command


The command for creating React.js application using ‘npx’ command is shown below:
npm install create-react-app -g
create react-app <project_name>

111
Awesome React.js

Chapter 4
Harnessing the Power of Components in React.js
4.1 Creating Components in React.js
The React.js component resides in a file with the extension .js or .jsx.

Difference Between .js and .jsx Files


The difference between .js and .jsx files lies in the syntax and usage:

.js Files
Files with the .js extension contain JavaScript code. They are typically used to write regular
JavaScript code that can be executed by the browser or a JavaScript runtime environment. .js
files can be used for various purposes, including defining functions, variables, classes, and
executing logic.

Example:
function greet() {
console.log('Hello, World!');
}

greet();

.jsx Files
Files with the .jsx extension contain JavaScript code with JSX syntax, which is an extension
to JavaScript introduced by React. JSX allows you to write HTML-like code within
JavaScript, making it easier to define and visualize the structure of React components.

Example:
import React from 'react';
function Greeting() {
return <h1>Hello, World!</h1>;

112
Awesome React.js
}
export default Greeting;

In .jsx files, you can define React components using JSX syntax, where HTML-like elements
and attributes can be used to describe the component's structure and content. JSX code needs
to be transpiled into regular JavaScript code using a tool like Babel before it can be executed
by the browser or JavaScript runtime.

React components defined in .jsx files can be used within other React components or
rendered by ReactDOM. The .jsx extension helps developers easily identify files that contain
React-specific code and utilize JSX syntax.

Note: While .jsx is the conventional extension for React components, React itself doesn't
require the use of .jsx files. React components can also be defined in .js files without JSX
syntax, using the React.createElement() method directly.

4.2 Types of Components in React.js


React.js supports the following two types of components:
● Stateless Functional Components
● Stateful Class Components

4.2.1 Stateless Functional Components


Function components in React are JavaScript functions that are used to render HTML and
describe the user interface (UI) of an application. Unlike class components, function
components do not have their own state. Instead, they are primarily used for generating JSX,
which is a syntax extension for JavaScript that allows for the representation of HTML-like
structures.

Function components are written as regular JavaScript functions and can optionally receive
data (props) as parameters. They return JSX elements that specify the desired HTML output
to be rendered in the browser. By passing props to function components, the rendered HTML
can be customized based on the provided input, allowing for dynamic and reusable
components.

113
Awesome React.js
These function components are also known as stateless components because they don't
manage or store any internal state within themselves. They rely on the data passed via props
and trigger updates by re-rendering when the props change. This simplicity and lack of state
management make functional components lightweight and easier to reason about.

Thus the function components in React serve as reusable units of UI code that receive data
via props, generate JSX to describe the desired HTML output, and render that HTML to the
browser. They are stateless and rely on external data to determine their rendering behaviour.

Functional Component Without props


The code snippet for defining a functional component without props is shown below:
function hello(){
return “<h1>Hello React.js</h1>”
}

Functional Component With props


The code snippet for defining a functional component using props for customizing the output
is shown below:
function hello(props){
return “<h1>Hello {props.name}</h1>”
}
The props is passed by the parent component which includes the <hello> component as
shown below:
<hello name=”SIBER”/>
{} denotes the JSX expression.

114
Awesome React.js
4.2.2 Stateful Class Components
Stateful class components in React extend the 'Component' class provided by the 'react'
library. They are responsible for rendering HTML that describes the user interface (UI) and
maintaining the state of the component.

Unlike stateless functional components, stateful class components have the ability to persist
and manage their own internal state. They define a 'render()' method that returns JSX
elements to describe the desired HTML output for the UI.

By extending the 'Component' class, stateful class components inherit a range of lifecycle
methods and features provided by React. These lifecycle methods allow for fine-grained
control over the component's behaviour at different stages of its lifecycle, such as
initialization, mounting, updating, and unmounting.

The state within stateful class components can be modified and updated using the 'setState()'
method, which triggers a re-rendering of the component with the updated state values. This
allows the UI to dynamically respond to changes in the component's state.

Hence the stateful class components in React extend the 'Component' class, have the ability to
maintain their own state, and define a 'render()' method to describe the UI using JSX. They
leverage React's lifecycle methods and the 'setState()' method to manage state updates and
ensure a responsive and interactive user interface.

Class components in React are more complex compared to functional components. They
require extending the 'React.Component' class and defining a 'render()' function that returns a
single React element. Unlike functional components, which can return multiple elements,
class components are limited to returning a single element from the 'render()' function.

Class components allow for passing data between different class components. They provide a
way to create reusable components that can communicate with each other by passing data
through props.

115
Awesome React.js
In React, a class component is essentially an ES6 class that can have its own internal state.
Similar to functional components, a class component can receive optional props as input and
return HTML as output. However, in addition to props, class components can also maintain
their own private internal state. This state can be used to generate the UI and can be updated
over time, triggering re-rendering of the component.

The ability to manage state within class components makes them suitable for handling
complex application logic and handling interactive user interfaces. By managing state, class
components can respond to user interactions and update the UI accordingly.

To summarize, class components in React are more complex than functional components.
They require extending the 'React.Component' class, have a single 'render()' function that
returns a React element, and enable the management of internal state. Class components
provide a way to pass data between components and are especially useful for handling
complex application logic and interactive UIs.

Creating Class Component in React.js


To create a class component in React.js, you can follow the steps outlined below:

Begin by creating a class that extends the 'Component' class provided by the 'react' library.
This class will serve as the blueprint for your component.

Inside the class, implement a 'render' method. This method is responsible for returning the
HTML elements that will generate the graphical user interface (GUI) for your component.
The 'render' method should return a single React element.

116
Awesome React.js
After defining the class component, export it so that it can be imported and used in other
components or files within your React application. This allows the component to be reused
and composed with other components.

To utilize the class component, import it into the desired file, such as 'App.js' or any other
component file where you want to use it. Importing the component makes it available for use
within that file.

By following these steps, you can create a class component in React.js that extends the
'Component' class, implements a 'render' method to generate the GUI, exports the component
for reusability, and imports it into other files where it needs to be used.
Class components are typically used when you need to manage state, handle lifecycle
methods, or perform more complex logic within your components.

Class Component Without props


The component class is inherited from React.Component class. Hence ‘React’ class residing
in the ‘react’ package must be imported.

The code snippet for defining a class component without props is shown below:
import React from “react”
class Hello extends React.component{
render(){
return “<h1>Hello React.js</h1>”
}
}

Class Component With props


The code snippet for defining a class component without props is shown below:
import React from “react”
class Hello extends React.component{
render(){
return “<h1>Hello {this.props.name}</h1>”
}

117
Awesome React.js
}

Note: Even if you don't explicitly define a constructor in a class component, you can still
access and use props within the component.
In class components, props are automatically available through the this.props object,
regardless of whether a constructor is implemented or not.

The following example demonstrates using the functional component in React.js. ‘Hello’ is a
functional component which is embedded by the parent component ‘App’ which passes a
name prop to the child component ‘Hello’.

hello.js

import React from “react”
class Hello extends React.component{
render(){
return “<h1>Hello {this.props.name}</h1>”
}
}

App.js

import './App.css';
import Hello from './components/hello';
function App() {
return (
<div className="App">
<Hello name="Poornima"/>
</div>
);
}
export default App;

118
Awesome React.js
On execution of the above application the following output is generated:

Exploring the Class Component


In the following example the above programme is rewritten using class component:
HelloComponent.js

import React, { Component } from 'react';
class HelloComponent extends Component {
render() {
return (
<div>
<h1> <font color='green'>Hello {this.props.name} </font></h1>
</div>
);
}
}
export default HelloComponent;
App.js

import './App.css';
import HelloComponent from './components/HelloComponent';
function App() {
return (
<div className="App">
<HelloComponent name="Poornima"/>
</div>

119
Awesome React.js
);
}
export default App;
On execution of the above application the following output is generated:

App Component
App component is a function component which returns HTML describing the GUI.

120
Awesome React.js
Modify the above ‘App.js’ file as shown in the following example:
App.js

import React, { Component } from 'react';
class App extends Component{
render(){
return (
<div>
<h1>App is Root Component of React Application</h1>
</div>
);
}
}
export default App;

To execute the application, enter the following command in the VSCode terminal
npm start

On execution of the above command the following output is generated:

Exploring Multiple Components in React.js


Create a folder with the name ‘components’ in ‘hello-world’ folder and create two
components with the names ‘FirstComponent.js’ and ‘SecondComponent.js’ in it and insert
in them the following code:

121
Awesome React.js
FirstComponent.js

import React, { Component } from 'react'
export class FirstComponent extends Component {
render() {
return (
<div><h2><font color='maroon'>First Component</font></h2></div>
)
}
}
export default FirstComponent

SecondComponent.js

import React, { Component } from 'react'
export class SecondComponent extends Component {
render() {
return (
<div><h2><font color='blue'>Second Component</font></h2></div>
)
}
}
export default SecondComponent

Next, include the two components in ‘App.js’ as shown below:

App.js

import React, { Component } from 'react';
import FirstComponent from './components/FirstComponent';
import SecondComponent from './components/SecondComponent';
class App extends Component{
render(){

122
Awesome React.js
return (
<div>
<h1>App is Root Component of React Application</h1>
<FirstComponent/>
<SecondComponent/>
</div>
);
}
}
export default App;

On execution of the above application the following output is generated. The ‘App’
component is rendered first followed by ‘FirstComponent’ and then ‘SecondComponent’.

4.3 Hands on Sessions with Functional and Class Components


Creating Functional Components in React.js
As described earlier, functional components in React.js are simply JavaScript functions
which optionally receive an object of properties referred to as ‘props’ and return HTML
describing the UI.

Create a folder with the name ‘components’ inside ‘hello-world’ folder. Inside ‘components’
folder create a file with the name ‘welcome.js’ and insert the following code in it.

123
Awesome React.js
welcome.js

import {Component} from 'react'
class Welcome extends Component{
render(){
return <h1>Welcome to React.js</h1>
}
}
export default Welcome

For using the ‘Welcome’ component in ‘App’ component we need to export it and import it
in App component.
Connect the component to the root component in ‘App.js’ as shown below:
App.js

import logo from './logo.svg';
import './App.css';
import Welcome from './components/welcome';
function App() {
return (
<div className="App">
<Welcome/>
</div>
);
}
export default App;
Switch to ‘hello-world’ folder and execute the React.js application by issuing the following
command:
npm start

The following output is generated:

124
Awesome React.js

Note: The render() method returns JSX.

Functional Vs. Class Component


Functional Component Class Component
It is a simple JavaScript class It is a class inherited from React.Component class
Functional components do not Provides in-built support for state management
possess their own internal state. which is managed using this.state object.
However, state management is
achieved through React hooks
useState.
Do not possess their own life cycle Possess their own life cycle methods for performing
methods. However, effect can be side effects and component updates.
achieved through useEffect hook.
The code is simple and concise. Code is complex compared to functional components
which involves constructor and different life cycle
methods:
 componentDidMount()
 componentDidUpdate()
 componentWillUnmount()
Functional components with React Class components have memory footprint little on
hooks are optimized for performance. higher side and hence are slower in performance
React hooks provide the functional compared to their functional counterparts.
components same capabilities as class
components in terms of state
management and life cycle
management.

125
Awesome React.js
4.4 Constructor in a React
The constructor in a React component holds significant importance as it is invoked prior to
the component's mounting phase. It serves as a crucial initialization point where you can
define the initial state and set up necessary bindings.

When implementing the constructor for a React component, it is essential to follow a specific
convention by calling the super(props) method as the very first statement. This ensures that
the parent class of the component (typically React.Component) is properly initialized before
accessing or modifying any properties or methods.

Consider the following polished code snippet that exemplifies the correct usage of the
constructor in a React component:

class MyComponent extends React.Component {


constructor(props) {
super(props); // The call to super(props) comes first
// Initialize state and perform any necessary setup
this.state = {
// Define initial state values
};
// Bind methods if necessary
this.handleClick = this.handleClick.bind(this);
}
// Other component methods and lifecycle hooks
// ...
render() {
// Component rendering logic
return (
// JSX markup
);
}
}

126
Awesome React.js
By adhering to this convention and ensuring that super(props) is the first statement in the
constructor, you establish a solid foundation for initializing the parent class and effectively
managing state and methods throughout the component's lifecycle. This approach promotes
code clarity and ensures the correct functioning of your React components.

The proper syntax for defining a constructor in React.js is shown below:

Syntax
Constructor(props){
super(props);
}

In React, constructors serve two main purposes:


Initializing the local state: Constructors are used to initialize the state of a component by
assigning an object to this.state. This allows the component to have its own internal state
data. The state members can be directly updated in the constructor, providing an initial value
for the state variables.

Binding event handler methods: Constructors are also used to bind event handler methods to
the component's events. This ensures that the methods are correctly associated with the
events and can be invoked when the events occur. By binding the methods in the constructor,
you ensure that the correct context is maintained when the methods are called.

It's important to note that the setState() method cannot be called directly inside the
constructor. If a component needs to use local state, the initial state should be assigned
directly to this.state within the constructor. The constructor is solely responsible for
initializing the initial state using this.state, and all other methods, except the constructor
itself, should use the setState() method to update the state.

By following these practices, constructors in React components effectively initialize the state
and bind event handler methods, contributing to the proper functioning and behaviour of the
component.

Note: If you do not call super(props) method, this.props will be undefined in the constructor
and can lead to bugs.

127
Awesome React.js
The following program attempts to access this.props without invoking super(props) which
will generate a compiler error.

App.js

import React, { Component } from 'react';
import FirstComponent from './components/FirstComponent';
import SecondComponent from './components/SecondComponent';
class App extends Component{
constructor(props) {
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",
}
}
render(){
return (
<div>
<div>
<h1><font color='green'>Profile : </font></h1>
{this.state.name}<br></br>
{this.state.designation}<br></br>
{this.state.institute}
</div>
</div>
);
}
}
App.defaultProps = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",

128
Awesome React.js
}
export default App;

On execution of the above program the following error message is displayed.

To fix the bug add super(props) statement to the constructor at the beginning as shown
below:

constructor(props) {
super(props)
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",
}

On execution of the program now the following output is generated:

129
Awesome React.js
Note:
For using the keyword ‘this’ inside a constructor you need to invoke super()
For using this.props inside the constructor you need to invoke super(props)

4.5 Defining State in Class Component


The following example demonstrates defining and using a state in a class component. React
state is an object which contains name/value pairs. The state can be set directly in the
constructor while setState() method is used for setting state in other methods of the
component class.
The following class component defines a state variable with the name ‘name’ and initializes
in the constructor and the same is rendered to the browser in the ‘render’ method.
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name:"Poornima Naik"
}
}
render(){
return (
<div>
<h1>Name : {this.state.name}</h1>
</div>
);
}
}
export default App;

Inside the class component, the state attribute is accessed using the following syntax:

130
Awesome React.js
this.state.<attribute_name>
On execution of the above application the following output is generated:

A Note on super(props)
In a class component, it is important to include a constructor and call super(props) as the first
line within the constructor. This is necessary to ensure that the parent class's constructor, in
this case, React.Component, is properly invoked and the component is initialized correctly.

The super(props) call is essential because it initializes the parent class, allowing it to set up
the necessary internal functionality of the component. It also passes the props object to the
parent class constructor, ensuring that the component can access and utilize the props passed
to it.

If you omit the super(props) call in the constructor, you will encounter an error. This is
because failing to call super(props) prevents the proper initialization of the parent class,
which can lead to unexpected behaviour or errors within your component.

By including the super(props) call in the constructor of a class component, you ensure that
the component inherits the necessary functionality from the parent class and can correctly
utilize the props passed to it.

Creating Functional Components in VSCode


Under ‘src’ folder create a new folder with the name ‘components’. All the new components
created will reside in this folder. Under ‘components’ folder create a new JavaScript file with
the name ‘hello.js’ as shown in the following figure:

131
Awesome React.js

Creating a functional component in React.js involves the following steps:


● Create a JavaScript file with the extension .js describing the functional component
● Export the component from the JavaScript file so that other components can import
and use it.
● Import the functional component in App.js file.
● Include the component in App.js file using the following syntax:
<Component_Name/>
Insert the following code in hello.js file created above:
hello.js

function Hello(){
return <h1> Hello React.js</h1>
}
export default Hello

The structure of App.js file is shown below:


The ‘Hello’ component from ‘components’ folder is automatically imported.

import Hello from './components/hello';


function App() {
return (
<div className="App">
<Hello/>
</div>
);

132
Awesome React.js
}
export default App;

Switch to ‘hello-world’ folder and execute the React.js application by issuing the following
command:
npm start

The following output is generated:

Our first functional component is up and running.

Using Arrow Function to Re-define the Functional Component


The functional component ‘Hello’ can be re-defined using the ES6 arrow function syntax as
shown below:
const Hello = () => {
return <h1> Hello React.js Again!</h1>
}
export default Hello

On execution of the application the following output is generated:

Next, if we want to make the project for the production mode, type the following command.
This command will generate the production build, which is best optimized.
npm run build

133
Awesome React.js
Exploring React State

In React, the information and data that a component needs to store and manage are typically
stored in its state. The state represents the current state of the component and can be updated
over time as the component transitions from one state to another.

The state of a component plays a crucial role in determining its behaviour and how it renders
in the user interface. By utilizing the component's state, you can create dynamic and
interactive components that respond to user interactions and other events.

Components that have state and utilize it to control their behaviour are referred to as
"stateful" components. These components are responsible for managing their own state and
updating it as needed.

The state in a component is local to that component and can only be accessed or modified
within the component itself. This encapsulation ensures that the state remains self-contained
and doesn't affect other components or the overall application state.

By leveraging state, stateful components can dynamically update their rendering based on
changes in the state values. This allows for a more interactive and responsive user experience,
as the component can adapt and display different content based on the current state.

The state in React components holds the necessary information and data, enabling
components to be dynamic and interactive. Stateful components manage their own state,
which determines their behaviour and how they render in the UI. The encapsulation of state
within a component ensures its independence and facilitates the creation of more interactive
user interfaces.
The state is assigned to the component using this.state property preferably in the constructor.
Note: Component state can be set inside the constructor directly by accessing ‘this.state’
property. However, outside the constructor setState() method is used for modifying the
property.

134
Awesome React.js
In the following example a state is defined with the three keys, ‘name’, ‘designation’ and
‘institute’ which are initialized in the constructor. Further the state is returned in the render
method through JSX.

app.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studies",
institute: "CSIBER, Kolhapur"
}
}
render(){
return (
<div>
<h1><font color='blue'>Profile : </font></h1>
<h2>Name : {this.state.name}</h2>
<h2>Designation : {this.state.designation}</h2>
<h2>Institute : {this.state.institute}</h2>
</div>
);
}
}
export default App;

On execution of the application the following output is generated:

135
Awesome React.js

The following example presents an improved version of the above program which changes
the ‘name’ attribute of a state on click of a button ‘Change Name’. In non-constructor
functions setState() method is employed for changing the state as demonstrated in the
following program. Further, if the event handler refers to ‘this’, the event handler must be
bound to ‘this’ keyword using the following syntax:

this.changeHandler = this.changeHandler.bind(this);

App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur"
}
}
changeHandler(){
this.state.name = "Dr. P.G.Naik"
}
render(){
return (
<div>

136
Awesome React.js
<h1><font color='blue'>Profile : </font></h1>
<h2>Name : {this.state.name}</h2>
<h2>Designation : {this.state.designation}</h2>
<h2>Institute : {this.state.institute}</h2>
<button type="button" onclick={this.changeHandler}>Change Name</button>
</div>
);
}
}
export default App;

On execution of the above program the following output is generated. The state is not
updated on clicking the ‘Change Name’ button. The reason for this is that the above code has
a flaw in changeHandler() function. The state cannot be directly updated. Instead, setState()
function is used for updating the state.

To fix the issue replace the changeHandler() function with the one shown below and re-
execute the program:

changeHandler(){
this.setState({
name:"Dr.P.G.Naik"
}
)
}

137
Awesome React.js
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)

this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur"
}
this.changeHandler = this.changeHandler.bind(this);
}

changeHandler(){
this.setState({
name:"Dr.P.G.Naik"
}
)
}
render(){
return (
<div>
<h1><font color='blue'>Profile : </font></h1>
<h2>Name : {this.state.name}</h2>
<h2>Designation : {this.state.designation}</h2>
<h2>Institute : {this.state.institute}</h2>
<button onClick={this.changeHandler}>Change Name</button>
</div>
);
}
}

138
Awesome React.js
export default App;

On execution of the application the following output is generated:

If the following line is removed from the above code


this.changeHandler = this.changeHandler.bind(this);
the following error message is displayed.

To get rid of the error, change the onClick handler of a button control as shown below:
<button onClick={this.changeHandler.bind(this)}>Change Name</button>

139
Awesome React.js

Example:
The following program hosts two buttons with the caption ‘View Profile’ and ‘Hide Profile’
which display and hide the profile on clicking a button.

App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",
viewProfile : false
}
}
viewProfile(){
this.setState({
viewProfile:true
}
)
}
hideProfile(){

140
Awesome React.js
this.setState({
viewProfile:false
}
)
}
render(){
if (this.state.viewProfile) {
return (
<div>
<div>
<h1><font color='blue'>Profile : </font></h1>
<h2>Name : {this.state.name}</h2>
<h2>Designation : {this.state.designation}</h2>
<h2>Institute : {this.state.institute}</h2>
</div>
<div>
<button onClick={this.viewProfile.bind(this)}>View Profile</button>
<button onClick={this.hideProfile.bind(this)}>Hide Profile</button>
</div>
</div>
);
}
else{
return (
<div>
<div>
<button onClick={this.viewProfile.bind(this)}>View Profile</button>
<button onClick={this.hideProfile.bind(this)}>Hide Profile</button>
</div>
</div>
)
}
}

141
Awesome React.js
}
export default App;
On execution of the application the following output is generated:

On clicking the ‘View Profile’ button the profile is displayed as shown below:

On clicking the ‘View Profile’ button the profile is hidden.

Defining State in Class Component


The following program presents storing an array in a state variable with the name ‘programs’.
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
programs:['MCA', 'MBA', 'MSW', 'MPhil']
}

142
Awesome React.js
}
render(){
return (
<div>
<h1>Programmes Launced by SIBER : </h1>
<ul>
{this.state.programs.map(program => <li><h2>{program}</h2></li>)}
</ul>
</div>
);
}
}
export default App;

On execution of the application the following output is generated:

4.6 More on Props in React


Exploring ‘props’ in Depth in React.js
Props in React are read-only properties that store the values of attributes for a component,
similar to HTML attributes. They facilitate communication between different components
within an application by allowing data to be passed from one component to another. Props

143
Awesome React.js
can be thought of as function arguments and can be passed to a component in a similar
manner.

One key aspect of props is that they are immutable, meaning they cannot be modified from
within a functional component. Once props are passed to a component, their values remain
constant throughout the component's lifecycle. This immutability ensures predictable
behaviour and helps maintain the integrity of data flow within the application.

By leveraging props, components can easily exchange information and customize their
behaviour based on the data received. This enables greater flexibility and reusability, as
components can be composed and combined in different ways, leveraging the power of data
passed through props.

Hence props in React are read-only properties that enable communication and data sharing
between components. They serve as a mechanism for passing data from one component to
another, similar to function arguments, and play a crucial role in creating modular, reusable,
and customizable components within a React application.

The key features of props can be summarized as follows:

 Props are passed as an object argument to functional components.


 Props expose properties that are assigned values from attributes defined in the
corresponding HTML tags, which determine the UI of the functional component.
 Props facilitate the transfer of data from one component to another, enabling
communication and sharing of information.
 Props are immutable, meaning their values cannot be changed once they are assigned.
This ensures consistency and predictability in the data flow within the component.
 In essence, props serve as a mechanism for passing data and configuring the
behaviour of functional components. They provide a way to transfer information
between components while maintaining the integrity and immutability of the data
being passed. By leveraging props effectively, React components can be designed to
be more modular, reusable, and adaptable.

Props in React refer to the immutable properties that components receive and use to
communicate with each other. They serve as the attribute counterparts of HTML tags,
providing a way to pass data from one component to another. Props are essential for

144
Awesome React.js
establishing communication and data flow between different components in a React
application.

Unlike state, props cannot be modified once they are assigned. They are similar to function
arguments, allowing components to receive external data and configure their behaviour
accordingly. Props are accessed within a component using the this.props property, providing
a means to retrieve and utilize the values passed to the component.

By leveraging props, React components can exchange information, customize their rendering,
and collaborate effectively within the application's ecosystem. The immutability of props
ensures that data remains consistent and reliable throughout the component hierarchy,
enhancing the predictability and maintainability of the application.

Hence props in React are immutable properties that enable communication and data transfer
between components. They serve as the attribute counterparts of HTML tags, providing a
mechanism for passing data from one component to another. Props operate similar to function
arguments and are accessible within components using the this.props property.

4.7 Default Props


Default props can be directly added to component class as demonstrated in the following
program:
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
}
render(){
return (
<div>
<div>
<h1><font color='green'>Profile : </font></h1>
<h2>Name : {this.props.name}</h2>
<h2>Designation : {this.props.designation}</h2>

145
Awesome React.js
<h2>Institute : {this.props.institute}</h2>
</div>
</div>
);
}
}
App.defaultProps = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",
}
export default App;

On execution of the application the following output is generated:

Dynamic components in React.js can be rendered by utilizing the flexibility of 'props'. Props
serve as optional inputs that components can accept to generate a customizable graphical user
interface (GUI). In the given example, we extend the 'Hello' component to incorporate a
'name' attribute as a prop. The 'Hello' component receives the 'name' prop and generates a
personalized greeting message for the user. Props are defined as attributes within the 'Hello'
component, and their values are passed from the parent component to the embedded child
component.

By leveraging props as attributes, components can dynamically receive data and adapt their
rendering based on the provided values. This enables components to be highly customizable
and reusable across different contexts within the application. Parent components have the

146
Awesome React.js
ability to pass specific data or configuration to child components, allowing for dynamic
generation of UI elements.

Thus, 'props' play a vital role in rendering dynamic components in React.js. They act as
optional inputs that enable components to receive data and generate a customizable GUI.
Props are specified as attributes within components and can be passed from parent
components to child components, allowing for dynamic content generation and enhancing the
flexibility and reusability of React components.

The different steps involved in defining and using ‘props’ in a functional component are
enumerated below:
1. Pass ‘props’ as a parameter to the functional component.
2. Use the following syntax for accessing the attribute using ‘props’
props.<attribute_name>
3. Define the attribute in ‘App’ component using the following syntax:
<component_name attr_name=attr.value>

In the following example, the ‘Hello’ component defines an attribute with the name ‘name’
which is accessed in the ‘Hello’ component using the syntax {props.name} which is a JSX
expression evaluated by React.js
Note: {} braces are used for evaluating the JSX expression.

The ‘App’ component which accesses the ‘Hello’ component passed the value to the ‘name’
attribute using the following syntax:
<Hello name="PGN"/>

Insert the following code in ‘hello.js’ and ‘app.js’ files.

hello.js

export const Hello = (props) => {
return <h1> <font color='red'>Hello {props.name}!</font></h1>
}
export default Hello
Insert the following code in ‘app.js’ as shown below:
app.js

147
Awesome React.js

import logo from './logo.svg';
import './App.css';
import Hello from './components/hello';
function App() {
return (
<div className="App">
<Hello name="PGN"/>
</div>
);
}
export default App;

Modify ‘App.js’ file as shown below to reuse the ‘Hello’ component multiple times in an
‘App’ component.
App.js

import logo from './logo.svg';
import './App.css';
import Hello from './components/hello';
function App() {
return (
<div className="App">
<Hello name="Poornima Naik"/>
<Hello name="Girish Naik"/>
</div>
);
}

148
Awesome React.js
export default App;

On executing the application now, the following output is generated in the browser:

Adding Multiple Attributes to the ‘Hello’ Component


Modify the ‘hello.js’ file as shown below which accesses two properties ‘name’ and ‘inst’
sent as attributes by <Hello> element.
hello.js

export const Hello = (props) => {
return <h1> <font color='red'>Hello {props.name} is currently working at <font
color='blue'> {props.inst}</font>!</font></h1>
}
export default Hello

Modify app.js file to specify the ‘name’ and ‘inst’ attributes in <Hello> element.
app,js

import logo from './logo.svg';
import './App.css';
import Hello from './components/hello';
function App() {
return (
<div className="App">
<Hello name="Poornima Naik" inst="CSIBER" />

149
Awesome React.js
<Hello name="Girish Naik" inst="KIT"/>
</div>
);
}
export default App;

On execution of the above program the following output is generated:

Limitations of Props
One notable limitation of 'props' in React is their immutability. When 'props' are passed from
a parent component to a child component, the child component can access and utilize them,
but it cannot modify or change their values. This immutability ensures that the data passed
from parent to child remains consistent and predictable.

To overcome this limitation and introduce mutability, React provides the concept of 'state'.
Unlike 'props', 'state' allows components to manage and modify their own internal data. By
utilizing 'state', components can maintain and update their data dynamically, responding to
user interactions or other events.

Unlike 'props', which are external inputs, 'state' is local to the component and can be modified
using the 'setState()' method. This allows components to be more dynamic and interactive, as
their behaviour can change based on the internal state values.

By combining 'props' and 'state', React components can achieve both immutability and
mutability, enabling the passing of data from parent to child through 'props' while allowing
components to manage their own dynamic behavior through 'state'.

While 'props' in React are immutable and passed from parent to child, their limitation is
overcome by utilizing 'state'. 'State' allows components to manage and modify their internal

150
Awesome React.js
data, introducing mutability and enabling dynamic behavior within the component. By
combining the use of 'props' and 'state', React components can achieve a balance of
immutability and mutability, resulting in more flexible and interactive applications.

Using Mutable Component State in React


Every React.js component returns JSX which defines the user interface.

4.8 Relative Comparison Between Props and State


Parameter Props State
Source Props are passed to the components as State is managed by the class
attributes from the parent component to the component using this.state
child component. object.
Mutability Props are immutable and cannot be modified State is mutable. State
by the child component. changes are asynchronous.
Access Props are accessed in functional components State is managed in class
using ‘props’ object while this.props object is component using this.state
used in class components. object while in functional
components useState React
hook is used for managing
state.
Application Props are employed for the communication State is used for managing
between the parent component and a child the component-specific data
component. that changes over time.
Props make the component re-usable. State does not render the
component reusable.
Scope Props can be accesses by the child State cannot be accessed by
components. child components.

Similarities Between Props and State


The component State and Props share some common similarities as depicted below:
Some similarities between props and state are listed below:

151
Awesome React.js
 Both are used for managing data within the React component. They are used for
passing and storing the information which decides how the component is rendered.
 Both of them are plain JavaScript objects.
 Both can contains default values.
 Both props and state trigger re-render when their values change.

The below table will guide you about the changing in props and state.

4.9 FAQs on Props and State


Q.1 Can a child component get initial value from parent component>
Yes using both props and state.

Child component getting initial value from parent component using


props.
In React, it is common to pass initial value from parent component to child component
through props. This enables the child component to receive and use the initial value during its
first render as demonstrated in the following code snippet.

ParentComponent.js

import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const initialValue = 'Hello, World!';
return (
<div>
<ChildComponent initialValue={initialValue} />
</div>
);
};
export default ParentComponent;

152
Awesome React.js
ChildComponent.js

import React from 'react';
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.initialValue
};
}
render() {
const { value } = this.state;
return (
<div>
<p>Initial Value: {value}</p>
</div>
);
}
}
export default ChildComponent;

App.js

import './App.css';
import ParentComponent from './components/ParentComponent';
function App() {
return (
<div className="App">
<ParentComponent/>
</div>
);
}
export default App;

153
Awesome React.js
In this example, the ParentComponent renders the ChildComponent and passes the
initialValue as a prop. The ChildComponent receives the prop as an argument in its
functional component declaration and can use the initialValue as needed.

By passing the initial value through props, you can ensure that the child component has
access to the value when it is first rendered and use it to initialize its state etc.

On execution of the above program the following output is generated:

Child component getting initial value from parent component using


state.
For using state in the child component to manage the initial value received from the parent
component, the child component must be converted into a class component and the
constructor and setState methods can be used for initializing the state as demonstrated in the
following code snippet.

ChildComponent.js

import React from 'react';
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.initialValue
};
}
render() {
const { value } = this.state;
return (

154
Awesome React.js
<div>
<p><font color='red'>Initial Value: {value}</font></p>
</div>
);
}
}
export default ChildComponent;

In this example, the ChildComponent is now a class component. The constructor method is
used to set the initial state of the component, using the initialValue prop passed from the
parent component.
The initial value is accessed in the child component's render method through this.state.value.
You can render and use the initial value as needed within the child component.
Using the state in the child component allows you to have control over the value and make
changes to it within the child component if necessary.

On execution of the above program the following output is generated:

Note: props passed by parent component can be accessed in both the functional child
components using ‘props’ as the function parameter and in class child component using a
constructor with ‘props’ as a parameter.

Q.2 Can props be changed by parent component?


Yes. If the parent component needs to update the data that is passed down to the child
component, it should update its own state and re-render the child component with the updated
props as demonstrated in the following code snippet which is the re-write of above parent
component.

155
Awesome React.js
ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [prop, setProp] = useState('Initial Value');

const updateProp = () => {


setProp('New Value');
};
return (
<div>
<ChildComponent prop={prop} />
<button onClick={updateProp}>Update Prop</button>
</div>
);
};
export default ParentComponent;

ChildComponent.js

import React from 'react';
const ChildComponent = ({ prop }) => {
return (
<div>
<p>Prop Value: {prop}</p>
</div>
);
};
export default ChildComponent;

In the above code snippet, the ParentComponent maintains the state for the ‘prop’ and hosts a
button for updating the value of ‘prop’. When the button is clicked, the ‘updateProp’ function

156
Awesome React.js
is invoked, updating the value of ‘prop’. As a result, the parent component re-renders, and the
new prop value is passed down to the child component, causing it to re-render as well with
the updated value.

On execution of the above program the following output is generated:

On clicking ‘Update Prop’ button the following output is generated:

Note: Props should be treated as immutable, and any changes to the value should be done in
the parent component by updating its state and passing down the updated value as a new prop
to the child component.

Q.3 Can set default values for the props and state inside the component?
Yes. Both the props and state can receive default values inside the component. Props with
default values is already discussed earlier. State can get default values inside the constructor.

For Props:
To assign default values to props, you can use the ‘defaultProps’ property, which allows you
to define default values for the props of a component as demonstrated in the following code
snippet.

157
Awesome React.js
MyComponent.js

import React from 'react';
const MyComponent = (props) => {
// Access the prop with default value
console.log(props.myProp);
return (
<div>
{/* Render the component */}
</div>
);
};
MyComponent.defaultProps = {
myProp: 'Default Value'
};
export default MyComponent;

App.js

import './App.css';
import MyComponent from './components/MyComponent';
function App() {
return (
<div className="App">
<MyComponent/>
</div>
);
}
export default App;

In the above code snippet, the ‘defaultProps’ property is assigned to the MyComponent
function component. It defines the default value for the ‘myProp’ prop. If the parent
component does not provide a value for the myProp prop, the default value will be used.

158
Awesome React.js
On execution of the above program the following output is generated:

For State:
To set default values for state in a class component, you can initialize the state object with
default values in the component's constructor method as demonstrated in the following code
snippet:

MyComponent.js

import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myState: 'Default Value'
};
}
render() {
// Access the state with default value

return (
<div>
<center><h3><font color="orange">{this.state.myState}</font></h3></center>
</div>
);
}
}
export default MyComponent;

159
Awesome React.js
In the above code snippet, the ‘myState’ property is initialized with a default value of
'Default Value' in the component's constructor method. If the state is not explicitly updated
by any subsequent actions, this default value will be used.

On execution of the above program the following output is generated:

By providing default values for props and state, you can ensure that the component behaves
as expected even when the parent component or any other external factors do not provide
specific values.

Q.4 Can props and state change inside the component?


Props cannot change inside the child component while state can change through
asynchronous setState() method as demonstrated earlier.

Q.5 Can set initial value for child component?


Yes, you can set an initial value for child components by passing it as a prop from the parent
component. This allows you to provide the child component with an initial value that it can
use when it is first rendered as described in Q.1.

Defining State in Class Components


State in React
The state in React represents an updatable data structure that holds information or data
specific to a component. It plays a crucial role in creating dynamic components that can adapt
and respond to user actions or system events. The state encapsulates the component's local
information and determines its behavior and rendering.

160
Awesome React.js
The state is accessible and modifiable only within the component itself. It provides a way for
the component to manage and update its internal data, facilitating interactivity and dynamic
behavior. While the state can be used only in class components, it is a powerful mechanism
for creating components that can maintain and manipulate their own data.

In the constructor of a class component, the state can be directly manipulated. However, in
other methods of the component, such as event handlers or lifecycle methods, the setState()
method is used to modify the state. This method triggers a re-rendering of the component,
ensuring that the updated state is reflected in the rendered UI.

The state in React represents an updatable data structure that holds component-specific
information. It enables the creation of dynamic components and governs their behavior and
rendering. The state can only be accessed and modified within the component itself and is
typically managed using the setState() method.

In ‘components’ folder create a new file with the name ‘state.js’.


Add a button to the UI with the caption ‘Change State’. On clicking the button, the state and
hence the text displayed should change.
Note: Props cannot be used for the purpose since they are immutable. Once the text is
displayed it cannot be changed. The solution is to use component state.

Insert the following code in ‘state.js’ file.


state.js

import {Component} from 'react'
class State extends Component{
constructor(){
super()
this.state={
msg : "React.js is interesting"
}
}
render(){
return <h1>{this.state.msg}</h1>
}

161
Awesome React.js
}
export default State

app.js

import logo from './logo.svg';
import './App.css';
import State from './components/state';
function App() {
return (
<div className="App">
<State/>
</div>
);
}
export default App;

On execution of the application the following output is generated:

Changing the State on Click of a Button


The following example represents the modified version of the above program which changes
the state on a button click.
Modify the code in ‘state.js’ file as shown below:
state.js

import {Component} from 'react'
class State extends Component{

162
Awesome React.js
constructor(){
super()
this.state={
msg : "React.js is interesting"
}
}
change(){
this.setState({
msg:"React.js is used for designing stunning user interfaces"
})
}
render(){
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick={()=>this.change()} >Change Message</button>
</div>
)
}
}
export default State
On execution of the above program the following output is generated:

Click on ‘Change Message’ button which changes the state variable ‘msg’ and the text
displayed on the browser window will accordingly change.

163
Awesome React.js

Note on Button Click Event Handler

<button onClick={()=>this.change()}>Change Message</button>

Using an arrow function as the onClick event handler in the above option is functional and
will work as expected. However, it's important to note that this approach can have
performance implications, particularly if the component frequently re-renders.

The reason behind this is that each time the component renders, a new instance of the arrow
function is created. This can lead to unnecessary memory allocation and potential
performance degradation, especially in components that are re-rendered frequently or have a
large number of instances.

To optimize performance, it is generally recommended to avoid using arrow functions


directly in the render method for event handlers unless it is necessary. Instead, consider
defining the event handler as a separate method within the component class. This way, the
method will be created only once and can be reused across multiple render cycles, resulting in
improved performance and reduced memory usage.

By following this recommendation, you can ensure that your React components maintain
optimal performance by minimizing unnecessary function instances and promoting efficient
rendering.

<button onClick={this.change}>Change Message</button>

This option correctly assigns the this.change method as the onClick event handler. When the
button is clicked, the this.change method will be called.

<button onClick={this.change()}>Change Message</button>

This option invokes the this.change method immediately when the component renders
because it includes parentheses () after this.change. As a result, the this.change method will

164
Awesome React.js
be called during rendering and not when the button is clicked. This is likely not the desired
behaviour.

Hence, the second option, <button onClick={this.change}>Change Message</button>, is


the correct way to assign the this.change method as the event handler for the button's onClick
event.

4.10 Combining State and Props


In a React application, it is indeed possible to combine both state and props to manage and
pass data between components. This can be demonstrated through the following program:

The state is typically set in the parent component, which serves as the source of truth for the
shared data. The parent component can then pass this data to its child components as props.
By passing the state as props, the child components can access and utilize the data provided
by the parent component.

This combination of state and props allows for a hierarchical data flow, where the parent
component manages the overall state and distributes it to its child components. The child
components can then use the received props to render their own UI or perform specific
actions based on the shared data.

By utilizing state in the parent component and passing it as props to child components, you
can establish communication and data sharing within your React application. This approach
enables components to stay synchronized and ensures that changes in the parent's state are
propagated down to the child components, allowing for a consistent and reactive user
interface.

Overall, combining state and props in a single React application provides a powerful
mechanism for managing and sharing data between components, enabling a flexible and
interconnected application structure.

Following example demonstrates combining state and props in a single application. In the
following example, the ‘App’ component defines a state with the attributes, ‘name’,
‘designation’ and ‘institute’ which are initialized in the constructor. The ‘App’ component
hosts two child components ‘FirstComponent’ and ‘SecondComponent’. The state attribute
‘name’ is passed to the ‘FirstComponent’ as a prop and the remaining state attributes

165
Awesome React.js
‘designation’ and ‘institute’ are passed as a prop to the ‘SecondComponent’. Both the child
components retrieve the prop values and render them as JSX to the browser.
App.js

import React, { Component } from 'react';
import FirstComponent from './components/FirstComponent';
import SecondComponent from './components/SecondComponent';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",
}
}
render(){
return (
<div>
<div>
<h1><font color='green'>Profile : </font></h1>
<FirstComponent name={this.state.name}/>
<SecondComponent designation={this.state.designation}
institute={this.state.institute}/>
</div>
</div>
);
}
}
App.defaultProps = {
name : "Dr. Poornima G. Naik",
designation : "HOD, Department of Computer Studied",
institute: "CSIBER, Kolhapur",

166
Awesome React.js
}
export default App;

FirstComponent.js

import React, { Component } from 'react'
export class FirstComponent extends Component {
render() {
return (
<div><h2><font color='maroon'>{this.props.name}</font></h2></div>
)
}
}
export default FirstComponent

SecondComponent.js

import React, { Component } from 'react'
export class SecondComponent extends Component {
render() {
return (
<div>
<h2><font color='blue'>{this.props.designation}</font></h2>
<h2><font color='blue'>{this.props.institute}</font></h2>
</div>
)
}
}
export default SecondComponent

167
Awesome React.js

More on this.props
In ‘components’ folder create a file with the name ‘ComponentA.js’ and insert the following
code in it:

ComponentA.js

import React, { Component } from 'react'
import ComponentB from './ComponentB'
export class ComponentA extends Component {
constructor(props) {
console.log(this.props)
}
render() {
return (
<h1>Testing this.props</h1>
)
}
}
export default ComponentA

Next, insert the ‘ComponentA’ in ‘App component.


App.js

import './App.css';
import ComponentA from './components/ComponentA';

168
Awesome React.js
function App() {
return (
<div className="App">
<ComponentA/>
</div>
);
}
export default App;
On execution of the above program, the following error message is displayed:

To get rid of the above error modify ComponentA as shown below and re-execute the
program. Add super(props) at the beginning of the constructor.
ComponentA.js

import React, { Component } from 'react'
import ComponentB from './ComponentB'
export class ComponentA extends Component {
constructor(props) {
super(props)
console.log(this.props)
}
render() {
return (

169
Awesome React.js
<h1>Testing this.props</h1>
)
}
}
export default ComponentA

On execution of the program now, the following output is generated:

Now, this.props is properly accessed but is blank.

However, this is not applicable if the constructor is not implemented. In this case the default
constructor will be invoked which handles the situation properly as demonstrated in the
following program which does not define a constructor. The value of this.props is logged to
the console on click of a button ‘Click Me’.

ComponentA.js

import React, { Component } from 'react'
import ComponentB from './ComponentB'
export class ComponentA extends Component {
test = () =>{
console.log(this.props)
}
render() {

170
Awesome React.js
return (
<div>
<h1>Testing this.props</h1>
<button onClick={this.test}>Click Me</button>
</div>
)
}
}
export default ComponentA
On execution of the above program the following output is generated:

On clicking he ‘Click Me’ button the value of this.props is logged to the console as shown
below:

Now, this.props can be accessed but is a blank object since no props is passed to the
‘ComponentA’.
To add props to ‘ComponentA’ modify the ‘App’ component as shown below:
App.js

import './App.css';
import ComponentA from './components/ComponentA';
function App() {
return (

171
Awesome React.js
<div className="App">
<ComponentA name="Poornima" institute="SIBER"/>
</div>
);
}
export default App;
On execution of the program now, the props are logged to the console on clicking the ‘Click
Me’ button as shown in the following figures:

setState()
This method is used to update the state of the component. This method does not always
replace the state immediately. Instead, it only adds changes to the original state. It is a
primary method that is used to update the user interface(UI) in response to event handlers and
server responses.

Note: In the ES6 classes, this.method.bind(this) is used to manually bind the setState()
method.

Syntax
this.stateState(object newState[, function callback]);

172
Awesome React.js
In the above syntax, there is an optional callback function which is executed once setState() is
completed and the component is re-rendered.

Pure Components in React.js


What is pure component?
In the context of React, a pure component refers to a specialized component that leverages
optimization techniques to enhance rendering efficiency. It is a class component that extends
the React.PureComponent class or a functional component created using the React.memo
higher-order component.

The distinguishing feature of pure components lies in their ability to intelligently determine
when re-rendering is necessary, thereby improving overall performance. By conducting a
shallow comparison of the incoming props and state against their previous values, pure
components ascertain if any actual changes have occurred. If no discernible differences are
detected, the component abstains from re-rendering, effectively sidestepping redundant
updates and optimizing the application's execution.

The shallow comparison mechanism examines only the top-level properties of the props and
state objects, rather than delving into nested structures. Consequently, it is crucial to exercise
caution when working with intricate data structures or mutable objects, as modifications
within nested properties may not trigger re-rendering. In such cases, it is advisable to ensure
immutability or employ alternative strategies to accurately update the state and props.

Pure components are particularly advantageous when dealing with large-scale applications or
components that undergo frequent updates but exhibit consistent rendering outcomes for
identical props and state combinations. By minimizing the number of re-renders, pure
components significantly enhance performance and bolster the overall responsiveness of the
application.

It is worth noting that React Hooks, introduced in React 16.8, offer an alternative approach to
achieving similar optimization goals. The useMemo and useCallback hooks allow for
memorization of values and callbacks, respectively, curtailing unnecessary recalculations and
re-renders. However, the concept of pure components remains relevant in codebases utilizing
class components and for specific use cases.

173
Awesome React.js
Difference Between Regular Component and a Pure Component
The main difference between a regular component and a pure component in React lies in how
they handle updates and re-rendering.

Regular Component
A regular component in React, either a class component or a functional component, doesn't
have built-in optimizations for rendering.
Whenever a regular component receives new props or its state changes, React triggers a re-
render, regardless of whether the new props or state are actually different from the previous
values.
As a result, regular components may re-render even if their props or state remain the same,
potentially causing unnecessary rendering and impacting performance.
To prevent unnecessary re-renders, regular components can implement their own logic to
perform manual checks and comparisons on props or state before deciding to render.

Pure Component
A pure component in React, typically a class component that extends React.PureComponent
or a functional component created with React.memo, implements automatic shallow prop and
state comparisons for rendering optimizations.
When a pure component receives new props or its state changes, it performs a shallow
comparison between the new and previous values.
If the shallow comparison determines that the props or state are the same, the pure component
avoids re-rendering altogether, saving processing power and improving performance.
Pure components are useful when components have frequent updates but exhibit consistent
rendering results for the same set of props and state. They help prevent unnecessary re-
renders in scenarios where the component's output would be unchanged.
Pure components are especially effective when dealing with large-scale applications or
components with complex rendering logic, as they automatically handle the optimization
process without requiring explicit manual checks.
Hence pure components in React provide an out-of-the-box optimization by automatically
handling shallow comparisons of props and state to avoid unnecessary re-renders. Regular

174
Awesome React.js
components lack this automatic optimization and may require manual checks and
comparisons to avoid unnecessary rendering.
Here's an example to illustrate how pure components work in React:
Counter.js

import React, { PureComponent } from 'react';
class Counter extends PureComponent {
render() {
console.log('Counter rendered');
return (
<div>
<h2>Counter: {this.props.count}</h2>
</div>
);
}
}
export default Counter;
app.js

import React from 'react';
import Counter from './components/Counter';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) => ({
count: prevState.count+1,
}));

175
Awesome React.js
}, 1000);
}
render() {
console.log('App rendered');
return (
<div>
<h1>App</h1>
<Counter count={this.state.count} />
</div>
);
}
}
export default App;
In the above example,
 we have an App component that renders a Counter component. The Counter
component displays a count value passed via props.
 The Counter component extends PureComponent, making it a pure component. It has
a render method that logs a message to the console every time it renders and displays
the count value.
 The App component initializes the count state to 0 and sets up an interval that
increments the count by 1 every second using setState. It also renders the Counter
component, passing the count value as a prop.
When you run this example, you'll notice that the App component re-renders every second
due to the interval. The Counter component also renders once initially and every 1 second
since the count value passed as props changes for subsequent updates.
The console output would be something like this:

176
Awesome React.js

Update the componentDidMount() life cycle method as sown below and re-execute the
program:
componentDidMount() {
setInterval(() => {
this.setState((prevState) => ({
count: prevState.count,
}));
}, 1000);
}
On re-executing the program the following output is generated:

177
Awesome React.js

As you can see, the Counter component only renders once initially and doesn't re-render
despite the App component's frequent updates since the count value does not change. This
behavior demonstrates the optimization achieved by pure components, as they avoid
unnecessary rendering when the props and state remain unchanged.
Note: The componentDidMount method is invoked during the initial mounting phase of the
App component. It is called after the component has been inserted into the DOM for the first
time which sets the timer for invoking the arrow function every 1 sec.

The working of the application is summarized below:


 The App component is created.
 The constructor of the App component is executed, initializing the count state to 0.
 The render method of the App component is called, generating the initial JSX
structure.

178
Awesome React.js
 The render method of the Counter component is also called, as it is included in the
App component's render tree.
 The App component is then mounted to the DOM, and the virtual representation of
the component is translated into real DOM nodes.
 Once the component is successfully mounted, the componentDidMount method of the
App component is invoked.
 Inside the componentDidMount method, an interval is set up to increment the count
state every 1000 milliseconds.
 The application continues to run, and the interval triggers the callback, updating the
state and causing re-renders of the App and Counter components.
 Therefore, the componentDidMount method is called once, specifically after the
initial rendering and mounting of the App component.
 The App component continues to render the same JSX structure repeatedly, as the
interval triggers the state updates and subsequent re-renders.
 With each state update caused by the interval, the render method of the App
component is called again to generate the updated JSX structure.
 The Counter component is also re-rendered due to the updated count prop received
from the App component.
 Therefore, the render method of the App component is called initially during the
mounting phase and subsequently on each state change caused by the interval,
triggering re-renders of both the App and Counter components.

Regular Component Pure Component


A regular component does not implement the A pure component on the otherhand
shouldComponentUpdate() method which implements the shouldComponentUpdate()
always returns true by default. method performing shallow comparison of
props.
It compares the current state with the
previous state or current prop with previous
prop and re-renders only if there is a
difference.

179
Awesome React.js
A Note on Shallow Comparison
Shallow Comparison of the Primitive Values
If x and y are two primitive types then x = = = y returns true if and only if both x and y have
the same values and type as demonstrated in the following program:
MyComponent.js

import React from 'react';
class MyComponent extends React.Component {
handleClick = () => {
var x=10;
var y=10;
console.log(x===y);
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default MyComponent;

On execution of the application the following output is generated:

180
Awesome React.js
On clicking the ‘Click Me’ button, the message ‘true’ is logged to the console.

Modify ‘MyComponent.js’ file as shown below:


MyComponent.js

import React from 'react';
class MyComponent extends React.Component {
handleClick = () => {
var x=10;
var y="10";
console.log(x===y);
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default MyComponent;

On execution of the application now, the message ‘false’ is logged to the console as shown in
the following figure:

181
Awesome React.js

Shallow Comparison of Complex Types


If arr1 and arr2 are two complex types (arrays) then arr1 = = = arr2 returns true if and only if
both of them point to the same array object. The same applies to the object comparison. If
obj1 and obj2 are two objects then obj1 = = = obj2 returns true if and only if both of them
reference the same object. The array and object comparison is demonstrated in the following
program:

Shallow Comparison of Arrays


MyComponent.js

import React from 'react';
class MyComponent extends React.Component {
handleClick = () => {
var x=[10,20,30];
var y=[10,20,30];
var z=x;
console.log(x===y);
console.log(x===z)
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}

182
Awesome React.js
export default MyComponent;

On execution of the program the following output is generated:

Shallow Comparison of Objects


MyComponent.js

import React from 'react';
class MyComponent extends React.Component {
handleClick = () => {
var obj1={x:10, y:20};
var obj2={x:10, y:20};
var obj3=obj1;
console.log(obj1===obj2);
console.log(obj1===obj3)
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default MyComponent;

On execution of the program the following output is generated:

183
Awesome React.js

Rendering List in a Pure Component


Here's an example of how you can use a pure component to render a list efficiently:
ListItem.js

import React, { PureComponent } from 'react';
class ListItem extends PureComponent {
render() {
const { item } = this.props;
console.log(`Rendering item: ${item.id}`);
return <li>{item.name}</li>;
}
}
export default ListItem;

List.js

import React from 'react';
import ListItem from './ListComponent';
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{ id: 1, name: 'Item 1' },

184
Awesome React.js
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
};
}
componentDidMount() {
setTimeout(() => {
this.setState((prevState) => ({
items: [
...prevState.items,
{ id: 4, name: 'Item 4' },
],
}));
}, 3000);
}
render() {
console.log('List rendered');
const { items } = this.state;
return (
<div>
<h2><font color='green'>List Component</font></h2>
<ul>
{items.map((item) => (
<ListItem key={item.id} item={item} />
))}
</ul>
</div>
);
}
}
export default List;

185
Awesome React.js
App.js

import React from 'react';
import List from './components/List';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) => ({
count: prevState.count,
}));
}, 5000);
}
render() {
console.log('App rendered');
return (
<div>
<h1><font color='red'>App Component</font></h1>
<List/>
</div>
);
}
}
export default App;
On execution of the above program the following output is generated:

186
Awesome React.js

187
Awesome React.js

n React, re-rendering of a component is triggered by changes in the component's state or


props. Even if the reference of the items array remains the same, React uses a process called
reconciliation to determine if the component needs to be re-rendered.

In the given example, when the setState method is called in the componentDidMount
lifecycle method, React internally performs a shallow comparison between the previous state
and the new state. Although the array reference remains the same, React detects that the
content of the array has changed because a new item is added.

React's reconciliation process then determines that the component needs to be re-rendered to
reflect the updated state. The virtual DOM is compared with the real DOM, and the necessary
changes are applied efficiently to update the UI.

188
Awesome React.js
It's important to note that React relies on immutable data patterns to optimize rendering.
Modifying the existing array directly, as mentioned earlier, would break this pattern and can
lead to unexpected behavior. Therefore, it's generally recommended to create a new array or
use array methods like ‘concat’ to append elements while maintaining immutability.

componentDidMount() {
setTimeout(() => {
const newItem = { id: 4, name: 'Item 4' };
this.setState(prevState => ({
items: prevState.items.concat(newItem),
}));
}, 3000);

import React from 'react';


import ListItem from './ListComponent';
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
newItemAdded: false,
};
}
componentDidMount() {
setTimeout(() => {
const newItem = { id: 4, name: 'Item 4' };
this.setState({
items: [...this.state.items, newItem],
newItemAdded: true,
});

189
Awesome React.js
}, 3000);
}
shouldComponentUpdate(nextProps, nextState) {
return !nextState.newItemAdded;
}
render() {
console.log('List rendered');
const { items } = this.state;
return (
<div>
<h2><font color='green'>List Component</font></h2>
<ul>
{items.map(item => (
<ListItem key={item.id} item={item} />
))}
</ul>
</div>
);
}
}
export default List;

On execution of the above program the following output is generated:

190
Awesome React.js
shouldComponentUpdate(nextProps, nextState) {
return nextState.newItemAdded;
}
With the above change in place, the following output is generated:

191
Awesome React.js
In this updated code, a new state property called newItemAdded is introduced, which is
initially set to false. When the new item is added to the items array, newItemAdded is set to
true.

The shouldComponentUpdate method is overridden to check the newItemAdded property in


the next state. If it's true, indicating that a new item has been added, the component will
update and re-render. If it's false, the component will not update and re-rendering will be
skipped.

By utilizing the newItemAdded property and customizing the shouldComponentUpdate


method, you can control the re-rendering behavior based on whether a new item has been
added to the items array.

In this example, we have a List component that renders a list of items using the ListItem pure
component. The List component has an initial array of items in its state.

The List component's render method maps over the items array and renders a ListItem for
each item, passing the item as a prop. The key attribute is provided to ensure efficient
reconciliation of list items.

The ListItem component extends PureComponent, making it a pure component. It renders


each list item and logs a message to the console indicating which item is being rendered.

In the componentDidMount method of the List component, we simulate an asynchronous


update after 3 seconds. This update adds a new item to the items array in the state.

When you run this example, you'll notice that the List component initially renders all the
items in the array, and the ListItem components render accordingly. After 3 seconds, the List
component updates its state with a new item. However, since the ListItem components are
pure components and the existing items remain unchanged, only the new item is rendered,
and the existing items are not re-rendered.

The console output would be something like this:

As you can see, the ListItem components render only once initially and then render again
when a new item is added to the list, optimizing the rendering process by avoiding
unnecessary re-renders of unchanged items.

192
Awesome React.js
Here's a simplified example of using a pure component to render a list:

import React, { PureComponent } from 'react';


class ListItem extends PureComponent {
render() {
const { item } = this.props;
return <li>{item}</li>;
}
}
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['Item 1', 'Item 2', 'Item 3'],
};
}
componentDidMount() {
setTimeout(() => {
this.setState((prevState) => ({
items: [...prevState.items, 'Item 4'],
}));
}, 3000);
}
render() {
const { items } = this.state;
return (
<div>
<h1>List</h1>
<ul>
{items.map((item, index) => (
<ListItem key={index} item={item} />
))}
</ul>
</div>

193
Awesome React.js
);
}
}
export default List;

In this simplified example, we have a List component that renders a list of items using the
ListItem pure component. The List component initializes an array of items in its state.

The List component's render method maps over the items array and renders a ListItem for
each item, passing the item as a prop. The key attribute is set to the index of the item to
ensure efficient reconciliation of list items.

The ListItem component extends PureComponent, making it a pure component. It renders


each list item.

In the componentDidMount method of the List component, we simulate an asynchronous


update after 3 seconds. This update adds a new item to the items array in the state.

When you run this code, you'll notice that the List component initially renders all the items in
the array, and the ListItem components render accordingly. After 3 seconds, the List
component updates its state with a new item. Since the ListItem components are pure
components and the existing items remain unchanged, only the new item is rendered, and the
existing items are not re-rendered.

This simplified code demonstrates the use of a pure component to optimize rendering when
rendering a list.

Here's an example of using a pure component to render an object efficiently:


Person.js

import React, { PureComponent } from 'react';
class Person extends PureComponent {
render() {
const { person } = this.props;
return (
<div>

194
Awesome React.js
<h2>Name: {person.name}</h2>
<h2>Age: {person.age}</h2>
</div>
);
}
}
export default Person
App.js

import React from 'react';
import Person from './components/Person';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
person: {
name: 'Maya Gupta',
age: 30,
},
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
person: {
...this.state.person,
age: 31,
},
});
}, 3000);
}
render() {
const { person } = this.state;

195
Awesome React.js
return (
<div>
<h1><font color='red'>App Component</font></h1>
<Person person={person} />
</div>
);
}
}
export default App;
On execution of the above application the following output is generated:

In this example, we have an App component that renders a Person component using a pure
component approach. The App component has a person object in its state.

196
Awesome React.js
The render method of the App component renders the Person component, passing the person
object as a prop.

The Person component extends PureComponent, making it a pure component. It renders the
name and age properties of the person object.

In the componentDidMount method of the App component, we simulate an asynchronous


update after 3 seconds. This update modifies the age property of the person object.

When you run this code, you'll notice that the App component initially renders the Person
component with the initial values from the person object. After 3 seconds, the App
component updates its state by modifying the age property of the person object. Since the
Person component is a pure component and the name property remains unchanged, only the
age property is updated in the rendered output.

The console output would be something like this:

As you can see, the Person component only renders once initially and then renders again
when the age property of the person object is updated. This behavior optimizes rendering by
avoiding unnecessary re-renders of unchanged properties.

Pure components are created by extending the PureComponent class from ‘react’ library
instead of ‘Component’ class.

RegularComponet.js

import React, { Component } from 'react'
export class RegularComponent extends Component {
render() {
console.log("Regular Component render method invoked....")
return (
<div>RegularComponent {this.props.name}</div>
)
}
}
export default RegularComponent

197
Awesome React.js
PureComponent.js

import React, { PureComponent } from 'react'
export class PureComponent1 extends PureComponent {
render() {
console.log("Pure Component render method invoked....")
return (
<div>PureComponent {this.props.name}</div>
)
}
}
export default PureComponent1

ParentComponent.js

import React, { Component, PureComponent } from 'react'
import RegularComponent from './RegularComponent'
import { PureComponent1 } from './PureComponent'
export class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
name: "Maya"
}
}
componentDidMount(){
setInterval(() => {
this.setState({
name:"Maya"
})
},
5000)
}

198
Awesome React.js
handleClick = ()=>{
this.setState({
name:"Milan"
})
}
render() {
console.log("Parent Component render method invoked....")
return (
<div>
Parent Component
<RegularComponent name={this.state.name}></RegularComponent>
<PureComponent1 name={this.state.name}></PureComponent1>
<button onClick={this.handleClick}>Change Prop</button>
</div>
)
}
}
export default ParentComponent

App.js

import logo from './logo.svg';
import './App.css';
import ParentComponent from './components/ParentComponent'
function App() {
return (
<div className="App">
<ParentComponent/>
</div>
)
}
export default App;

199
Awesome React.js
On execution of the application the following output is generated:

Initially parent component, regular component and pure components are rendered. Then
onwards every 5 sec only parent and regular components are rendered since there is not
change in state variable ‘name’.

On clicking the ‘Change prop’ button the state variable ‘name’ changes from ‘Maya’ to
‘Milan’ as shown in the following figure.

200
Awesome React.js
Due to the change in the state variable ‘name’ the pure component re-renders. After 5 sec the
name changes back to ‘Maya’ resulting once again the re-rendering of pure component as
shown in the following figure:

To summarize:
 A pure component is created by extending the React.PureComponent class.
 A pure component implements the shouldComponentUpdate() life cycle method
which performs a shallow comparison on the props and state of the component to take
a decision about re-rendering.
 If there is no difference, the component is not re-rendered resulting inn performance
boosting.
 Ensure that all the child components of a pre component are also pure in order to
avoid an unexpected behaviour.

201
Awesome React.js
 For the complex types never mutate the state. Always return a new object reflecting
the new state.

Exploring Context in React.js


Contexts enable passing of data through the component tree without the need to pass props
down manually through each level.

Need for Context

In the above component hierarchy there are three levels of nesting. Suppose AppComponent
wants to pass data to any of the leaf level components, then currently the only way is to pass
it through the various intermediate levels as props (For example language preference prop).
For example, to pass the data to ComponentF, the data is first passed to ComponentC and
ComponentE. Hence even if the intermediate components do not need the data we need to
send the prop through them to be able for them to send the data further down the tree. This
further has security implications. This poses a problem in the case of deep levels of nesting.
What is desirable is sending the props directly to the required components without having to
manually drill down the props trough every level of the component tree. This is where the
Context comes into picture. Context APIs enable directly passing the prop to the required
components in a component tree. With the help of Context API the prop can be passed
directly from AppComponent to ComponentF without going through the intermediate
components, ComponentC and ComponentE.

202
Awesome React.js

Steps in Using the Context


Three major steps in using the context are depicted below:
Step 1: Create a Context
Step 2: Provide a context value.
Step 3: Consume the context value in the necessary components.

Creating a Context Object


Use the createContext function from the 'react' module to create a new context object. This
object will hold the state and provide it to the components that consume the context.

import React from 'react';


const MyContext = React.createContext();
const MyProvider = MyContext.Provider
const MyConsumer = MyContext.Consumer
export {MyProvider, MyConsumer}

Providing a context value.


<MyProvider value={/* Your value here */}>
{/* Components that consume the context */}
</MyProvider>

import React, {Component} from ‘react’


import ComponentC from ‘./components/ComponentC’
import {MyProvider} from ‘./components/MyContext’
function App() {
return (
<div className="App">
<MyProvider value=’CSIBER’>
<ComponentC/>
</MyProvider> </div>
)

203
Awesome React.js
}
export default App;
The context value can be consumed by ComponentC and any component below it in the
component tree.

Consume the context value in ComponentF


To consume the context value we need the consumer component. It encloses an arrow
function where the value is passed as a parameter which can be consumed in the function
body as shown in the following code snippet.
<MyConsumer>
{value => (
// Render JSX based on the context value
)}
</MyConsumer>
Function is passed as a child to MyConsumer. Function returns JSX based on the context
value.
import React, { Component } from 'react'
import {Consumer} from './Context1'
export class ComponentC extends Component {
render() {
return (
<MyConsumer>
{
name => {
return <h2> Hello {name}</h2>
}
}
</MyConsumer>
)
}
}
export default ComponentC

204
Awesome React.js
Every context object created using the createContext() method comes with the provider and
consumer react components. The provider object is required for storing the state in context
and consumer object is required for consuming the state from the context. Hence the provider
and consumer objects need to be exported.

Example:
The following example demonstrates using the context for sharing value between different
components of an application.
Create the following three components in ‘components’ folder. ComponentA contains
ComponentB and ComponentB contains ComponentC.

ComponentA.js

import React, { Component } from 'react'
import ComponentB from './ComponentB'
export class ComponentA extends Component {
render() {
return (
<ComponentB/>
)
}
}
export default ComponentA
ComponentB.js

import React, { Component } from 'react'
import ComponentC from './ComponentC'
export class ComponentB extends Component {
render() {
return (
<ComponentC/>
)
}

205
Awesome React.js
}
export default ComponentB
ComponentC.js

import React, { Component } from 'react'
import {Consumer} from './Context1'
export class ComponentC extends Component {
render() {
return (
<Consumer>
{
name => {
return <h2> Hello {name}</h2>
}
}
</Consumer>
)
}
}
export default ComponentC
Context1.js

import React from 'react'
const context=React.createContext()
const Provider=context.Provider
const Consumer=context.Consumer
export {Provider, Consumer}

App.js

import logo from './logo.svg';
import './App.css';
import ComponentA from './components/ComponentA';

206
Awesome React.js
import {Provider} from './components//Context1'
function App() {
return (
<div className="App">
<Provider value="PGN">
<ComponentA/>
</Provider>
</div>
)
}
export default App;

Workflow of Application
The following figure depicts the workflow of the application:

ComponentC is a nested component of ComponentA.


On execution of the application the following output is generated:

207
Awesome React.js

The following program presents the modified version n of the above program which sets a
default value for the context. The default value is set while creating the context. It is passed
as a parameter to the React.createContext() method as shown below:
Context1.js

import React from 'react'
const context=React.createContext('CSIBER')
const Provider=context.Provider
const Consumer=context.Consumer
export {Provider, Consumer}

With the default value in place there is no need of <Provider> element in App Component. If
the <Provider> tag is inserted it will consume the value provided by the provider. Hence if
<provider> tag is missing then default value will be consumed.
App.js

import logo from './logo.svg';
import './App.css';
import ComponentA from './components/ComponentA';
import {Provider} from './components//Context1'
function App() {
return (
<div className="App">
<ComponentA/>
</div>
)
}

208
Awesome React.js
export default App;

On execution of the application the following output is generated:

Exploring contextType
The contextType property is used when you are working with class components in React. It
allows you to assign a context to a static property of the class. The different steps involve in
exploring contextType are depicted below:

Step 1: Create a Context and Export it


First, create a context using React.createContext() as shown:
const MyContext = React.createContext();
export default MyContext

Step 2: Create a Class Component:


Create your class component where you want to consume the context. Make sure it extends
the React.Component class. Assign the Context to contextType property of the component
OR assign the context to the contextType static property of the class component. This will
link the context to the component.

class MyClassComponent extends React.Component {


// ...
}
MyClassComponent.contextType = MyContext;
OR

209
Awesome React.js
class MyClassComponent extends React.Component {
static contextType = MyContext;
// ...
}
Step 3: Access the Context Value
Now you can access the context value using this.context within the class component's
methods.
class MyClassComponent extends React.Component {
componentDidMount() {
const contextValue = this.context; // Access the context value
// Do something with the context value
}
render() {
const contextValue = this.context; // Access the context value
// Render JSX based on the context value
return (
// JSX code
);
}
}

Note: The contextType property can only be used in class components, and it allows you to
consume a single context within the component.

Remember, with the introduction of hooks in React, it is recommended to use the useContext
hook instead of contextType for consuming contexts in functional components.

Limitations Offered by contextType


Different limitations offered by contextType are listed below:
Restricted to Single Context: The contextType approach confines you to consuming only a
single context within a class component. If you require access to multiple contexts,
alternative methods, such as using the Context.Consumer component or exploring different
approaches, become necessary.

210
Awesome React.js
Limited to Class Components: The utilization of contextType is exclusive to class
components. This means that if you are working with functional components, you cannot
employ contextType and should instead opt for the more suitable useContext hook for
consuming contexts.

Inability to Automatically Cascade: The context assigned via contextType is not


automatically propagated to nested components. To consume the context in nested
components, you must explicitly pass the context value as props or employ the
Context.Consumer component within those components.

Testing Challenges: When testing components that employ contextType, mocking the
context value can prove to be arduous. It may necessitate the use of third-party libraries or
intricate setups to effectively mock the context for testing purposes.

Considering these limitations, it is advisable to leverage the useContext hook when


consuming contexts in functional components. This approach offers increased flexibility and
simplified testing capabilities compared to relying on contextType.

211
Awesome React.js

Chapter 5
Mastering the Basics of Event Handing in React.js
5.1 Exploring React Events
React provides its own event handling system called Synthetic Events, which closely
resembles the event handling mechanism used for DOM elements. Synthetic Events act as a
wrapper around the native events provided by the browser, offering a consistent interface
across different browsers.

The purpose of Synthetic Events is to abstract away the differences between browser
implementations and provide a unified event system that works consistently across all
supported browsers. By using Synthetic Events, developers can write event handlers in a
similar manner to handling events on regular HTML elements.

Synthetic Events provide a convenient way to handle user interactions and respond to events
within a React component. They capture events such as clicks, keyboard input, form
submissions, and more. With Synthetic Events, developers can write event handlers that are
compatible with React's component-based architecture, allowing for more controlled and
declarative handling of user interactions.

In summary, React's Synthetic Events are a specialized event handling system that wraps the
native events of the browser. They provide a consistent interface for handling events within
React components, allowing developers to write event handlers that work across different
browsers and maintain compatibility with React's component model.

5.2 Synthetic Event in React


In React, a synthetic event refers to a wrapper created by React around the native browser
event. It serves as an abstraction layer that ensures consistent event handling across various
browsers and platforms.

The purpose of the synthetic event system in React is to provide a standardized interface for
event handling, abstracting away the differences in how events are implemented by different
browsers. Whenever an event occurs, React generates a synthetic event object and passes it as
an argument to the event handler function.

212
Awesome React.js
The synthetic event object contains relevant information about the event, such as the event
type, target element, coordinates, and more. It offers methods and properties that mirror the
native browser event interface, enabling developers to interact with the event in a consistent
and predictable manner.

One notable advantage of synthetic events is their performance optimization. React employs
event pooling, where synthetic events are reused to improve performance. When an event
handler is invoked, the synthetic event object is recycled, and its properties are reset. If
there's a need to access event properties asynchronously, the event.persist() method can be
called to remove the event from the pool, preventing its properties from being cleared.

Hence React's synthetic event system provides a uniform way to handle events, ensuring
compatibility across different browsers. By utilizing synthetic events, developers can write
event handlers that work reliably and efficiently, contributing to the overall stability and
performance of React applications.

The following example demonstrates using a synthetic event in a React component:


MyComponent.js

import React from 'react'
class SyntheticEvent extends React.Component {
handleClick = (event) => {
console.log(event.type); // Accessing the event type
console.log(event.target); // Accessing the target element
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}
export default SyntheticEvent

213
Awesome React.js
App.js

import './App.css';
import SyntheticEvent from './components/SyntheticEvent';
function App() {
return (
<div className="App">
<SyntheticEvent/>
</div>
);
}
export default App;
In this example, the handleClick method is an event handler for the onClick event of a button.
When the button is clicked, React creates a synthetic event object and passes it to the
handleClick method. Inside the method, you can access properties of the synthetic event, such
as event.type for the event type and event.target for the target element.

On execution of the above program the following output is generated:

On clicking the ‘Click Me’ button the type and target of event are logged to the console as
shown in the following figure:

214
Awesome React.js
Hence, the synthetic event system in React provides a consistent and convenient way to
handle events across different browsers. It abstracts away browser inconsistencies and
simplifies event handling in React components.

Event Handling in React.js


The following figure depicts event handling in React.js where both the DOM and React
virtual DOM participate.

Some Noteworthy Points in Handling Events in React


When it comes to handling events in React, there are a few syntactic differences compared to
handling events on the DOM. These differences can be summarized as follows:

Naming Convention: React events use camel case naming instead of lowercase. For instance,
instead of using ‘onclick’ or ‘onchange’ we use ‘onClick’ or ‘onChange’, respectively.

Event Handler: In JSX, we pass a function as the event handler, rather than a string as used in
traditional DOM event handling. This allows for more flexibility and direct function
invocation.

Preventing Default Behavior: Unlike in traditional DOM event handling where we can return
false to prevent the default behavior, in React, we need to explicitly call the preventDefault
method on the event object to prevent the default behavior from occurring.

These syntactic differences in event handling with React ensure consistency and alignment
with JSX syntax. By following these conventions, developers can effectively handle events
within React components while maintaining code readability and adhering to best practices.

215
Awesome React.js
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
institute : ""
}
}
changeHandler = (event) => {
this.setState({institute : event.target.value})
}
render(){
return (
<div>
<form>
<h1>React Event Demo</h1>
<label>Name:
<input type="text" onChange={this.changeHandler}/>
</label>
<input type="submit" value="Submit" />
<h2><font color='blue'>Name of Institute : {this.state.institute}</font></h2>
</form>
</div>
);
}
}
export default App;
On execution of the above application the following output is generated:

216
Awesome React.js

5.3 Event Handling with Regular Function Expressions Without


Using State
Event Handling in Class Component
When using a regular function expression for event handling in React, a new function is
created during each render cycle. This means that a new instance of the function is created
every time the component is rendered, which can impact performance, particularly if the
component is re-rendered frequently or used within child components that undergo frequent
re-renders.

This performance issue arises because creating a new function instance during each render
cycle can lead to unnecessary memory allocation and garbage collection overhead. It can also
hinder performance optimizations such as memorization and component reusability.

To mitigate this performance impact, it is generally recommended to use memorization


techniques or to bind event handlers in the component's constructor. By doing so, we can
ensure that the event handler function is created only once and reused across render cycles,
improving performance and avoiding unnecessary function creations.

Here's an example that demonstrates the potential performance impact when using a regular
function expression for event handling:

class MyComponent extends React.Component {


handleClick() {
// Event handling logic here
}
render() {
return <button onClick={this.handleClick}>Click me</button>;

217
Awesome React.js
}
}
In the above example, the handleClick function is recreated during each render cycle, which
can lead to performance degradation. To optimize it, we can either use memorization
techniques or bind the event handler in the constructor:

class MyComponent extends React.Component {


constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Event handling logic here
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
By binding the event handler in the constructor, we ensure that the function is created only
once, improving performance and avoiding unnecessary function creations during each
render cycle.

EventComponent.js

import React from 'react'
class EventComponent extends React.Component {
handleClick() {
console.log('Button Clicked...')
}

render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);

218
Awesome React.js
}
}
export default EventComponent

App.js

import './App.css';
import EventComponent from './components/EventComponent';
function App() {
return (
<div className="App">
<EventComponent/>
</div>
);
}
export default App;

On execution of the above application the following output is generated:

On clicking the button the message ‘Button Clicked…’ is logged to the console.

5.4 Event Handling in Functional Component


The above program can be rewritten using a functional component, which has a slightly
different syntax for event handling. One notable difference is the absence of the this keyword

219
Awesome React.js
when invoking the event handler function. Here's an example that demonstrates the revised
code:

import React from 'react';


const MyComponent = () => {
const handleClick = () => {
// Event handling logic here
};
return (
<button onClick={handleClick}>Click me</button>
);
};
export default MyComponent;

In the functional component, the event handler function handleClick is defined within the
component's body. When the button is clicked, the handleClick function is invoked directly
without using the this keyword.

Functional components in React allow us to define event handlers as regular functions within
the component's body, making the code more concise and easier to read.

EventComponent1.js

import React, {useState} from 'react'
function EventComponent1() {
function handleClick() {
console.log('Button Clicked...')
}
return (
<div>Event Handling in Functional Component<br></br><br></br>
<button onClick={handleClick}>Click Me</button>
</div>
)
}
export default EventComponent1

220
Awesome React.js
App.js

import './App.css';
import EventComponent1 from './components/EventComponent1';
function App() {
return (
<div className="App">
<EventComponent1/>
</div>
);
}
export default App;
On execution of the above application the following output is generated:

On clicking the button the message ‘Button Clicked…’ is logged to the console.

In this example, the handleClick() method is a regular function defined within the component
class. The method is passed as a reference to the onClick prop of the button component.
When the button is clicked, the handleClick() method is invoked. The only difference
between the two is the way prop is passed to button component.
In class component ‘this’ keyword is used as shown below:
<button onClick={this.handleClick}>Click Me</button>
In functional component, however, only function name is used as shown below:

221
Awesome React.js
<button onClick={handleClick}>Click Me</button>
The possible flaw in code for the beginners is as follows:
<button onClick={handleClick()}>Click Me</button>
In the above statement handleClick() method is invoked when the component is rendered and
on clicking the button the handleClick() event handler is not executed.

On execution of the application the following output is generated:

and the following message is logged to the console:

Click on the button several times. It has no effect.

5.5 Event Handling with Regular Function Expressions Using State


setState() is invoked Asynchronously
When using a regular function expression for event handling in React, it's crucial to consider
the binding of the this keyword. Unlike arrow functions, regular functions don't automatically
bind this to the component instance. To access the component's instance properties or
methods within a regular function, you need to manually bind the function using the bind()
method or use alternative techniques such as arrow functions.

If you intend to refer to the component's instance using this inside a regular function, it's
necessary to explicitly bind the function with the component's instance using the bind()
method. This ensures that the function has the correct this context when invoked.

222
Awesome React.js
By being mindful of the binding of the this keyword, you can ensure that your event handling
functions in React components work as expected and maintain the proper access to
component-specific properties and methods.

This is demonstrated in the following example:


EventComponent.js

import React from 'react'
class EventComponent extends React.Component {
constructor(props){
super(props)
this.state={
programme : "MCA"
}
console.log("Initial State :",this.state.programme)
}
handleClick() {
this.setState({programme:"MSC"})
console.log("New State :",this.state.programme)
}
render() {
return (
<button onClick={this.handleClick}>Change State</button>
);
}
}
export default EventComponent
App.js

import './App.css';
import EventComponent from './components/EventComponent';
function App() {
return (
<div className="App">

223
Awesome React.js
<EventComponent/>
</div>
);
}
export default App;

On execution of the above application the following output is generated:

On clicking ‘changeState’ button the following error message is displayed:

224
Awesome React.js
The reason for this is the event handler is not bound to ‘this’ keyword. To fix the issue add
the following statement to the constructor as shown below:

EventComponent.js

import React from 'react'
class EventComponent extends React.Component {
constructor(props){
super(props)
this.state={
programme : "MCA"
}
console.log("Initial State :",this.state.programme)
this.handleClick=this.handleClick.bind(this)
}
handleClick() {
this.setState({programme:"MSC"})
console.log("New State :",this.state.programme)
}
render() {
return (
<button onClick={this.handleClick}>Change State</button>
);
}
}
export default EventComponent

On execution of the above application now the following output is generated:

225
Awesome React.js

There is a flaw in the above code.


In the above code, when you log the state immediately after calling this.setState({
programme: "MSC" }), (setState method is invoked asynchronously) you might observe that
the logged state still shows the old value. This is because setState is asynchronous in nature,
and the updated state may not be immediately available after calling setState.

There are two approaches to deal with this issue.


In the first approach ‘async’ keyword is used for defining asynchronous function and then
await keyword is used with setState() method to block the execution of next statement until
setState() returns and the state is updated.
Note: await keyword can only be used from within async function.

The second approach to access the updated state immediately after calling setState, you can
pass a callback function as the second argument to setState. This callback function will be
executed after the state has been updated. Here's how you can modify your code to log the
new state correctly:

Approach 1: Using Async Function.


The following example presents using await method inside async function for allowing state
updation to commence before its value is logged to the console.

EventComponent.js

import React from 'react'
class EventComponent extends React.Component {
constructor(props){

226
Awesome React.js
super(props)
this.state={
programme : "MCA"
}
console.log("Initial State :",this.state.programme)
this.handleClick=this.handleClick.bind(this)
}
async handleClick() {
await this.setState({programme:"MSC"})
console.log("New State :",this.state.programme)
}
render() {
return (
<button onClick={this.handleClick}>Change State</button>
);
}
}
export default EventComponent

On execution of the application the following output is generated:

227
Awesome React.js

Approach 2:
The following program demonstrates the use of callback function in handling asynchronous
events. In this case the setState() method takes two parameters.
 The first parameter is the state variable to be updated.
 The second parameter is the callback function which is executed only after the state is
updated.

EventComponent.js

import React from 'react';
class EventComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
programme: "MCA"
};
console.log("Initial State:", this.state.programme);
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState({ programme: "MSC" }, () => {
console.log("New State:", this.state.programme);

228
Awesome React.js
});
}
render() {
return (
<button onClick={this.handleClick}>Change State</button>
);
}
}
export default EventComponent;

In this case, bind(this) is used in the constructor to bind the this context of the handleClick
method to the component instance. This ensures that this within handleClick refers to the
component instance, allowing access to its properties and methods.
On execution of the above program the same output is generated as above.

5.6 Event Handling Using Arrow Functions


Arrow functions in React have a lexical this binding, which means that the this value within
an arrow function is automatically bound to the component instance. Unlike regular
functions, arrow functions inherit the this context from the surrounding scope.

Using arrow functions for event handling in React eliminates the need to manually bind the
function or concern oneself with potential issues of losing the correct this context. This
makes arrow functions a convenient and concise approach for handling events, as the this
keyword within the arrow function refers to the expected component instance.

By leveraging arrow functions, you can write cleaner and more concise event handlers in
React components, ensuring that the this context is correctly maintained without the need for
explicit binding.

EventComponent.js

import React from 'react';
class EventComponent extends React.Component {
constructor(props) {
super(props);

229
Awesome React.js
this.state = {
programme: "MCA"
};
console.log("Initial State:", this.state.programme);
}

handleClick = () => {
this.setState({ programme: "MSC" }, () => {
console.log("New State:", this.state.programme);
});
}
render() {
return (
<button onClick={this.handleClick}>Change State</button>
);
}
}
export default EventComponent;

In this case, the handleClick method is an arrow function defined within the class instance.
The function automatically inherits the this context from the class instance, allowing direct
access to its properties and methods.
On execution of the above application the following output is generated:

On clicking the ‘Change State’ button the following message is logged to the console.

230
Awesome React.js

In this example, the handleClick property is defined as an arrow function within the class
instance. This arrow function automatically binds to the component instance, allowing you to
access the component's properties and methods using this within the function.

It is important to note that when using arrow functions for event handling in React, a new
function is still created on each render. However, due to the consistent lexical this binding of
arrow functions, the performance impact is typically minimal.

In React, you have the flexibility to choose between regular function expressions and arrow
functions for event handling. Arrow functions provide a convenient way to handle events
with an inherent this binding, while regular functions require explicit binding or alternative
techniques to maintain the correct this context. When making a choice, consider both the
performance implications and whether you need to access the component instance within the
event handler.

Note: While using arrow functions it is not required to explicitly bind the event handler to
‘this’ keyword as in regular functions.

Significance of Arrow Functions in Event Handling


Arrow functions, introduced in the ES6 standard, offer a convenient feature for handling
functions in JavaScript. They eliminate the need for manually binding the 'this' keyword to a
specific context, as they have a lexical 'this' scope that is not restricted to any particular
calling function. When using arrow functions, the 'this' scope is automatically inherited from
the surrounding context.

With arrow functions, you can simplify event handling in React components by avoiding the
explicit binding of 'this' inside the constructor. The global scope of 'this' provided by arrow

231
Awesome React.js
functions eliminates the need for explicit binding, making the code more concise and
readable.

By utilizing arrow functions, you can streamline your code and enhance the overall
development experience by eliminating the complexities associated with 'this' binding.

Syntax:
variable_name = () => {
// implementation code
}
In React, event handling can be done using regular function expressions or arrow functions.
Both approaches have their own implications and considerations.

5.7 Event Handling in Class Components


The above program is re-written in class component as shown below:
click1.js

import React, { Component } from 'react';
class ComponentClick extends Component {
clickMe(){
console.log("Button Clicked Again")
}
render() {
return (
<div>
<button onClick={this.clickMe}>Click Me</button>
</div>
);
}
}
export default ComponentClick;

232
Awesome React.js
app.js

import logo from './logo.svg';
import './App.css';
import ComponentClick from './components/click1';

function App() {
return (
<div className="App">
<ComponentClick/>
</div>
);
}
export default App;
On execution of the above application the following output is generated:

The message ‘Button Clicked Again’ is logged to the console as shown below:

233
Awesome React.js
When it comes to invoking an event handler in React, there is a difference between functional
components and class components. In a functional component, the event handler can be
invoked directly without using the 'this' keyword. This is because functional components do
not define or have access to the 'this' keyword.

In a functional component, the event handler can be called simply by using its name, such as
'clickMe()', without the need for 'this.clickMe()'. This streamlined syntax allows for more
concise and straightforward event handling in functional components.

On the other hand, in a class component, the event handler needs to be invoked using the 'this'
keyword, such as 'this.clickMe()', to reference the specific instance of the component where
the event handler is defined.

Understanding the distinction between invoking event handlers in functional and class
components is important when working with React, as it helps ensure proper handling and
execution of events based on the component type.

<button onClick={clickMe}>Click Me</button>


While in class component ‘this’ keyword is used for invoking the event handler as shown
below:
<button onClick={this.clickMe}>Click Me</button>

Changing State Outside the Constructor


In the given example, the 'ComponentClick' component defines a state variable called 'msg'
and initializes it in the constructor. When the 'Click Me Now' button is clicked, it triggers the
'change()' method of the component class.

Inside the 'change()' method, the state variable 'msg' is updated. This means that when the
button is clicked, the value of 'msg' will change. This change in state will then trigger a re-
render of the component, reflecting the updated value in the rendered output.

The code snippet below illustrates the implementation:

class ComponentClick extends React.Component {


constructor(props) {
super(props);
this.state = {

234
Awesome React.js
msg: "Initial message",
};
}
change() {
this.setState({
msg: "Updated message",
});
}
render() {
return (
<div>
<h2>{this.state.msg}</h2>
<button onClick={this.change.bind(this)}>Click Me Now</button>
</div>
);
}
}
The above code snippet demonstrates how to update the state of a component by invoking a
class method when a button is clicked. The updated state is then reflected in the rendered
output, allowing for dynamic and interactive user interfaces in React.

click1.js

import React, { Component } from 'react';
class ComponentClick extends Component {
constructor(props){
super(props)
this.state={
msg:"Hello"
}
console.log(this.state.msg)
}
change(){
this.setState({

235
Awesome React.js
msg:"Good Bye"
}
)
console.log(this.state.msg)
}
render() {
return (
<div>
<button onClick={this.change}>Click Me Now</button>
</div>
);
}
}
export default ComponentClick;

However, on execution of the above program the following error message is generated. The
reason for the error message is that the ‘this’ keyword is used inside the change() method
which is the event handler for the click method and the change() method is not bound to ‘this’
keyword.

236
Awesome React.js
5.8 Binding Event Handler to an Event in React.js
To bind an event handler to ‘this’ keyword use the following syntax:
<button onClick={this.change.bind(this)}>Click Me Now</button>
The binding can be performed at two places:
 In the component constructor
 In the <button> element as shown above.
The following program demonstrates binding an event handler to ‘this’ keyword in the
component constructor.
app.js

import React, { Component } from 'react';
class ComponentClick extends Component {
constructor(props){
super(props)
this.state={
msg:"Hello"
}
this.change=this.change.bind(this)
console.log(this.state.msg)
}
change(){
this.setState({
msg:"Good Bye"
}
)
console.log(this.state.msg)
}
render() {
return (
<div>
<button onClick={this.change}>Click Me Now</button>
</div>
);

237
Awesome React.js
}
}
export default ComponentClick;
On execution of the application the following output is generated:

On clicking the ‘Click Me Now’ button the changed state variable ‘name’ is logged to the
console as shown in the following figure:

Child Component Communicating with Parent Component Using


‘props’
Passing Methods as ‘props’ in Child Component
The different steps involved in child component invoking the methods of parent component
are enumerated below:

In the parent component define a method which is assigned as a value to the prop of child
component.

238
Awesome React.js
In the child component access the parent component method using the prop passed to the
child component from the parent component.

The following example demonstrates this. The step-by-step working of the application is
enumerated below:

 The parent component defines a method with the name sayHello() as shown below:
sayHello(name1){
alert(`Hello from ${this.state.name} to ${name1}`)
}
 sayHello() method is passed as a value to the ‘greetHandler’ prop passed to the child
component.
<Child greetHandler={this.sayHello}/>

 ‘props’ is passed as a parameter to the child component and the sayHello() function of
parent component passed as a value of greetHandler prop is invoked in a child
component.
function Child(props) {
return (
<div>
<button onClick={()=>props.greetHandler('Dr.G.R.Naik')}>Greet</button>
</div>
);
}
The implementation of the code is shown below:
ParentComponent.js

import React, { Component } from 'react';
import Child from './Child';
class ParentComponent extends Component {
constructor(props){
super(props)
this.state={

239
Awesome React.js
name:"Dr.P.G.Naik"
}
this.sayHello=this.sayHello.bind(this)
}
sayHello(name1){
alert(`Hello from ${this.state.name} to ${name1}`)
}
render() {
return (
<div>
<Child greetHandler={this.sayHello}/>
</div>
);
}
}
export default ParentComponent;

Child.js

import React from 'react';
function Child(props) {
return (
<div>
<button onClick={()=>props.greetHandler('Dr.G.R.Naik')}>Greet</button>
</div>
);
}
export default Child
Finally, invoke the parent component from ‘App’ component as shown below:

240
Awesome React.js
app.js

import logo from './logo.svg';
import './App.css';
import ParentComponent from './components/ParentComponent';
function App() {
return (
<div className="App">
<ParentComponent/>
</div>
);
}
export default App;
On execution of the application the following output is generated:

Some Noteworthy Points About Event Handling in React


When handling events in React, it is important to follow certain rules and conventions:
 Event attributes should be written in camel case notation, such as onClick, onChange,
etc.
 In class components, the event handler function is specified as a prop value using the
syntax:
<button onClick={this.eventHandlerFunction} />
 However, in functional components, the 'this' keyword is not used:
<button onClick={eventHandlerFunction} />

241
Awesome React.js
 If you need to access the 'this' keyword within the event handler function of a class
component, you must bind the function to 'this' in the constructor:
 this.eventHandlerFunction = this.eventHandlerFunction.bind(this);

Arrow functions, on the other hand, have an automatic binding to the component instance.
This means that you can directly access the component's properties and methods without
explicitly binding them. Arrow functions provide a convenient way to handle events while
maintaining the correct 'this' context.

Following these rules ensures proper event handling in React components, allowing for
interactive and dynamic user interfaces.

To maintain the correct this context when accessing a component's instance properties or
methods, you should use the bind() method to manually bind the this context of a regular
function expression. On the other hand, arrow functions automatically inherit the correct this
context from their surrounding scope and do not require explicit binding.

When passing event handlers as props to React components, React takes care of preserving
the this context for you, regardless of whether you use regular function expressions or arrow
functions. This ensures that the event handlers can access the component's instance properties
and methods correctly.

By understanding the differences between regular function expressions and arrow functions
in terms of this binding, you can choose the appropriate approach for handling events in your
React components, while ensuring the correct this context is maintained.

5.9 Rendering a List in React


The following example demonstrates defining array state variable with the name ‘programs’.
The list of programmes is then rendered in the browser using map() method.
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {

242
Awesome React.js
programs:['MCA', 'MBA', 'MSW', 'MPhil']
}
}
render(){
return (
<div>
<h1>Programmes Launced by SIBER : </h1>
<ul>
{this.state.programs.map(program => <li><h2>{program}</h2></li>)}
</ul>
</div>
);
}
}
export default App;
On execution of the application the following output is generated.

5.10 A Note on ‘export default’ Keyword


When a functional component is exported using the 'export default' keyword, it can be
imported in another component with any chosen name. The imported component can be
assigned any arbitrary name based on the developer's preference or the naming conventions
followed in the project. This provides flexibility in naming the imported component while
ensuring its functionality can be utilized in the importing component.

243
Awesome React.js
In the following example, the component ‘Hello’ exported with ‘export default’ keyword is
imported as ‘TestComponent’ and is used in App component with the custom tag
<TestComponent></TestComponent>

Insert the following code in ‘hello.js’ file:


const Hello = () => {
return <h1> <font color='red'>Hello React.js Again!</font></h1>
}
export default Hello

Rewrite the ‘app.js’ file as shown below:


app.js

import logo from './logo.svg';
import './App.css';
import TestComponent from './components/hello';
function App() {
return (
<div className="App">
<TestComponent/>
</div>
);
}
export default App;

On execution of the application the following output is generated:

244
Awesome React.js
Name Export
In name export the component must be exported with exactly the same name with which it is
exported.
Switch back to ‘hello.js’ and export the component using name export as shown below:
hello.js

export const Hello = () => {
return <h1> <font color='red'>Hello React.js Again!</font></h1>
}
export Hello

With the above change if you try to execute the application now, the following error message
is generated:

Since the export and import names are different, the following error message is generated in
the browser.

To fix the issue, switch back to ‘app.js’ file and change the import statement as shown below:

245
Awesome React.js
app.js

import logo from './logo.svg';
import './App.css';
import Hello from './components/hello';
function App() {
return (
<div className="App">
<Hello/>
</div>
);
}
export default App;

Named and unnamed components in React.js

Named Component
In React, a named component refers to a component that has a specific name assigned to it. It
can be a functional component or a class component.

A named functional component is simply a JavaScript function that returns JSX. It is


typically written using the function declaration syntax or arrow function syntax and is named
with a capitalized identifier. Here's an example of a named functional component:

function MyComponent() {
return <div>Hello, I'm a named functional component!</div>;
}

The above function can be re-written using arrow function syntax as shown below:
const MyComponent = () => {
return <div>Hello, I'm a named functional component!</div>;
};

246
Awesome React.js
A named class component is a JavaScript class that extends the React.Component class. It
must have a render method that returns JSX. The class name is typically capitalized. Here's
an example of a named class component:

class MyComponent extends React.Component {


render() {
return <div>Hello, I'm a named class component!</div>;
}
}

Both named functional components and named class components can be imported, exported,
and used in other parts of your React application. They allow you to encapsulate reusable UI
logic and render dynamic content based on props and state.

Anonymous or Unnamed Components


In addition to named components, another category of components in React is the anonymous
or unnamed components. These components do not have a specific name assigned to them
and are typically used for rendering inline or as children of other components.
Anonymous functional components are created using arrow function syntax and are
commonly defined within the scope of another component. Here's an example of an
anonymous functional component:

const MyComponent = () => {


return (
<div>
Hello, I'm an anonymous functional component!
</div>
);
};
In this example, MyComponent is an anonymous functional component because it is assigned
to a constant variable without a specific name.

247
Awesome React.js
Anonymous class components, on the other hand, are created using class expressions and are
defined inline within the scope of another component. Here's an example of an anonymous
class component:

const MyComponent = class extends React.Component {


render() {
return (
<div>
Hello, I'm an anonymous class component!
</div>
);
}
};
In this example, MyComponent is an anonymous class component because it is assigned to a
constant variable without a specific name.

Anonymous components are often used when you need a simple component for rendering a
specific piece of UI logic without the need for reusability or when you need to define a
component inline without the need for a separate file.

A Note on Importing Components


When importing components in React, there is no inherent difference between importing
named components and unnamed components. The difference lies in how the components are
exported and how they are referenced in the importing file.

Importing Named Components


When a component is exported using a named export, it can be imported using curly braces
{} and the exact name of the exported component. For example, if you have a component
named MyComponent exported as a named export, you can import it like this:
import { MyComponent } from './components';

Here, MyComponent refers to the specific component that was exported with the name
MyComponent.

248
Awesome React.js
Importing Unnamed Components
Unnamed components, also known as default exports, are exported using the default
keyword. When importing an unnamed component, you can choose any name you prefer for
the imported component. For example, if you have an unnamed component exported as a
default export, you can import it like this:
import MyComponent from './components';

Here, MyComponent can be any name you choose. It represents the component that was
exported as the default export.

Note: A module can have multiple named exports, but only one default export. When
importing multiple named exports from a module, you need to specify their names within
curly braces and separate them with commas.
Example of importing multiple named components:
import { Component1, Component2 } from './components';
In summary, the difference between importing named and unnamed components in React lies
in how they are exported and how they are referenced in the importing file. Named
components are imported using their specific names within curly braces, while unnamed
components are imported using any name of your choice, as they are the default export.

Following table summarizes the different scenarios that may arise in imports.
Exported As Imported As
export function MyComponent() { import { MyComponent } from
} './path/to/module';

function MyComponent() { import xyz from './path/to/module';


} where ‘xyz’ is any name given to the imported
export default MyComponent component.
function MyComponent() { import { MyComponent } from
} './path/to/module';
export MyComponent
MyComponent = () { Error. Named exports cannot be used with

249
Awesome React.js
} unnamed components. Only default exports can
export MyComponent be used with unnamed components.
To export unnamed component use the
following syntax:
export MyComponent = () {
}

MyComponent = () { import MyComponent from './path/to/module';


}
export default MyComponent
export const namedExport1 = () => { import { namedExport1, namedExport2,
// Function implementation for namedExport3 } from './path/to/module';
namedExport1
};

export const namedExport2 = () => {


// Function implementation for
namedExport2
};

export const namedExport3 = () => {


// Function implementation for
namedExport3
};
const namedExport1 = () => { import { namedExport1, namedExport2,
// Function implementation for namedExport3 } from './path/to/module'
namedExport1
};

const namedExport2 = () => {


// Function implementation for
namedExport2
};

250
Awesome React.js

const namedExport3 = () => {


// Function implementation for
namedExport3
};

export { namedExport1, namedExport2,


namedExport3 };

Named exports are typically used with named components or functions. In JavaScript, named
exports allow you to export multiple components or functions from a module using specific
names. However, to use named exports, you need to assign a name to the component or
function you want to export.

If you have an unnamed component or function, you can only export it as the default export.
The default export allows you to import and use the component or function with a name of
your choice during the import.

Here's an example of exporting an unnamed component as the default export:


const MyComponent = () => {
// Component implementation goes here
};
export default MyComponent;

In this case, you can import and use the unnamed component as the default export in a
different module.

Difference Between export MyComponent and export


{MyComponent} Statements
The difference between export { MyComponent } and export MyComponent lies in the way
they export the component.

251
Awesome React.js
export { MyComponent }
This syntax is used for named exports. It means that you are explicitly exporting the
MyComponent component as a named export. When you use this syntax, you need to import
it using the curly braces {} in the import statement, like
import { MyComponent } from './path/to/module';

export MyComponent
This syntax is also used for named exports. It means that you are exporting the
MyComponent component as the named export of the module. . When you use this syntax,
you need to import it using the curly braces {} in the import statement, like
import { MyComponent } from './path/to/module';
{} is normally used for multiple named exports.

Here's a summary of the differences:


export { MyComponent } is used for named exports and requires importing with curly braces
{}.
export MyComponent is used for default exports and allows importing with any chosen
name.

It's worth noting that you can have both named exports and a default export in the same
module. For example:
export { namedExport1, namedExport2 };
export default MyComponent;

The following statement will generate an error since only one default export is allowed in a
module, however any no. of named exports are allowed.
export module1, module2

The following table summarizes different cases:

252
Awesome React.js
Export Statement Meaning
export MyComponent1 Named export of module1
export { MyComponent1} Named export of module1
export default MyComponent1 Default export of module1
export { MyComponent1, Named export of module1, module2,….
MyComponent2,. . .}
export MyComponent1; Error. Exporting named components requires curly
export MyComponent2; brackets.
export MyComponent1, Error. Exporting named components requires curly
MyComponent2,. . . brackets.

In this case, you can import the named exports and the default export separately in different
import statements.

5.11 React Snippets


React snippets play a vital role in speeding up the workflow.
A React snippet is a compact and reusable code segment that serves a specific purpose or
provides a particular functionality. These code snippets are designed to improve developer
productivity by offering pre-defined templates for commonly used React code patterns or
components in a project. By using snippets, developers can streamline the process of writing
code by automatically inserting frequently used code patterns into their project. This
automation helps save time and effort while ensuring consistency and efficiency in code
development.

React snippets can be created using various tools and extensions available for popular code
editors, such as Visual Studio Code (VSCode) or Atom. These snippets often include
boilerplate code for the following:

 React components
 state management
 lifecycle methods
 event handling, and
 other common React patterns.

253
Awesome React.js
How to Use React Snippets
When utilizing a React snippet, you usually input a designated trigger word or abbreviation
for the desired React template, followed by a keyboard shortcut or the press of the Tab key.
This action prompts the code editor to expand the snippet into a complete code block. The
expanded snippet can then be further customized by replacing placeholder values with actual
code or data that pertains to your particular use case. This streamlined process allows
developers to quickly incorporate standardized code structures and accelerate their coding
workflow while retaining the flexibility to adapt the snippet to suit their specific
requirements.

For example, a common React snippet might be used to create a functional component with
some initial structure:
import React from 'react';
const MyComponent = () => {
return (
<div>
{/* Component contents */}
</div>
);
};
export default MyComponent;

By leveraging React snippets, you can eliminate the need to manually type out the complete
component structure and instead rely on the snippet to generate the initial code structure for
you.

React snippets offer a significant advantage in terms of development efficiency and


maintaining code consistency across projects. They serve as a valuable tool for accelerating
development by providing a swift and convenient way to incorporate frequently used code
patterns. These snippets can be tailored to suit your individual preferences or shared within
teams, fostering a cohesive coding style and promoting consistency within an organization.

For using React snippets in VSCode follow the steps enumerated below:
Open any browser and enter the following URL in the address bar of a browser:
https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets

254
Awesome React.js
Click on ‘Install’ button.

The page opens in VSCode as shown below:

Click on ‘Install’ button to install React snippets in VSCode.

Testing React Snippets in VSCode


To test the React Snippets in VSCode, create a file with the extension .js type rc, all the
snippets starting with ‘rc’ are displayed as shown in the following figure:

255
Awesome React.js

Event Handling in Functional Components Using React Snippets


In ‘components’ folder create a file with the name ‘click.js’ and insert the following code in
it.
click.js

import React from 'react';
function FunctionClick(props) {
function clickMe(){
console.log("Button Clicked")
}
return (
<div>
<button onClick={clickMe}>Click Me</button>
</div>
);
}
export default FunctionClick;

Next, include the <FunctionClick> component in ‘app.js’ file as shown below:


app.js

import logo from './logo.svg';
import './App.css';

256
Awesome React.js
import FunctionClick from './components/click';
function App() {
return (
<div className="App">
<FunctionClick/>
</div>
);
}
export default App;
On executing the application the following output is generated.

On clicking the button, the message ‘Button Clicked’ is logged to the console as shown in the
following figure:

5.12 Exploring Conditional Rendering in React


In a React application, the ability to render multiple components and dynamically determine
which component to display is achieved through conditional rendering. Similar to JavaScript,
conditional rendering in React relies on control statements and operators to generate elements
that represent the current state of the application. By leveraging these constructs, the React
component can seamlessly update the user interface (UI) based on the specified conditions.

257
Awesome React.js
This approach empowers developers to create flexible and interactive UIs that adapt and
respond to changes in the application's state.

JSX rendered in React.js can be customized using conditional rendering employing one of
the four methods described below:
 Using if..else statement
 Using element variables
 Using ternary conditional operator.
 Using short-circuit operator.

The following examples demonstrate using the above four methods for rendering the JSX
based on the current value of a boolean state variable ‘isAdmin’.

Method 1: Using if..else Statement


In the provided example, conditional rendering is implemented using an if..else statement to
determine which message to display based on the value stored in the state variable 'isAdmin'.
If the variable holds the value 'true', the message "You have permissions to update the
database" is rendered. Conversely, if the variable does not have the value 'true', the message
"You do not have permissions to update the database" is rendered instead. This approach
allows for dynamic rendering of content based on the application's state, providing users with
customized messages based on their permissions.

conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
if (this.state.isAdmin){

258
Awesome React.js
return (
<div><h2>You have permissions to update database</h2></div>
)
}
else{
return (
<div><h2>You do not have permissions to update database</h2></div>
)
}
}
}
export default UpdateDatabase;

App.js

import logo from './logo.svg';
import './App.css';
import UpdateDatabase from './components/conditional';
function App() {
return (
<div className="App">
<UpdateDatabase/>
</div>
);
}
export default App;

On execution of the application the following output is generated:

259
Awesome React.js

Replace the statement


this.state={
isAdmin:true
}
with the one shown below
this.state={
isAdmin:false
}
and re-execute the application.

With the above change in place, the following output is generated:

Method 2: Using Element Variables


In the modified example, the message to be rendered is determined by assigning it to the
variable 'msg' based on the value of the state variable 'isAdmin'. If 'isAdmin' is true, the
message "You have permissions to update the database" is assigned to 'msg'. Otherwise, if
'isAdmin' is false, the message "You do not have permissions to update the database" is
assigned to 'msg'. Subsequently, the value stored in 'msg' is rendered to the browser,
displaying the appropriate message based on the condition. This approach allows for dynamic
rendering of different messages based on the state of the application.

260
Awesome React.js
conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
let msg
if (this.state.isAdmin){
msg=<div><h2>You have previledges to update database</h2></div>
}
else{
msg=<div><h2>You do not have previledges to update database</h2></div>
}
return <div>{msg}</div>
}
}
export default UpdateDatabase;

On execution of the application the following output is generated:

Replace the statement


this.state={
isAdmin:true
}

261
Awesome React.js
with the one shown below
this.state={
isAdmin:false
}
and re-execute the application.

Method 3: Using Ternary Conditional Operator


The above example is re-written below using the ternary conditional operator which takes the
following format:
this.state.isAdmin?< render msg1>:<render msg2>
In the above statement ‘msg1’ is rendered to the browser if the value stored in
this.state.isAdmin is true, otherwise ‘msg2’ is rendered.

The complete source code to achieve this is shown below:


conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {

262
Awesome React.js
return(
this.state.isAdmin?
<div><h2><font color='blue'>You have previledges to update
database</font></h2></div>:
<div><h2><font color='red'>You do not have previledges to update
database</font></h2></div>
)
}
}
export default UpdateDatabase;
On execution of the application the following output is generated:

Method 4: Using Short Circuit Operator


In the following example, the short-circuit operator is used for displaying the message on the
browser window if the value stored in the state variable this.state.isAdmin is true, otherwise
no message is displayed. The format of short-circuit operator is
this.state.isAdmin && <render msg>
In the above statement, the message is rendered to the browser if and only if the value of
this.state.isAdmin is true, otherwise nothing is rendered.

263
Awesome React.js
import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
return(
this.state.isAdmin && <div><h2><font color='green'>You have previledges to update
database</font></h2></div>
)
}
}
export default UpdateDatabase;
On execution of the application the following output is generated:

Application of Conditional Rendering in Authentication Example


In the given authentication example, there are two mutually exclusive buttons: 'Login' and
'Logout'. Only one of these buttons will appear at a time, depending on the user's
authentication status. If the user is not logged in, the 'Login' button will be rendered on the
user interface. Conversely, if the user is logged in, the 'Logout' button will be rendered
instead. Both the 'Login' and 'Logout' buttons are implemented as separate components. This

264
Awesome React.js
scenario in React is known as conditional rendering, where the rendering of components is
determined by certain conditions or states of the application.

There is more than one way to do conditional rendering in React as listed below:
 Using conditional ‘if’ statement.

 Using ternary conditional operator

 Using logical short circuit && operator

 Using switch case operator

 Conditional Rendering with enums

Using logical short circuit && operator


UserLoggedIn.js

import React, { Component } from 'react'
export class UserLoggedIn extends Component {
render() {
return (
<div>{<h2><font color='maroon'>Welcome User!</font></h2>}</div>
)
}
}
export default UserLoggedIn

GuestLoggedIn.js

import React from 'react'
function GuestLoggedIn() {
return (
<div><h2><font color='blue'>Welcome Guest!</font></h2></div>
)
}
export default UserLoggedIn

265
Awesome React.js
App.js

import React, { Component } from 'react';
import UserLoggedIn from './components/UserLoggedIn'
class App extends Component{
constructor(props) {
super(props)
this.state = {
isLoggedIn : true
}
}
render(){
return (
this.state.isLoggedIn && <UserLoggedIn />
);
}
}
export default App;
On execution of the above application the following output is generated:

Using Ternary Conditional Operator


App.js

import React, { Component } from 'react';
import UserLoggedIn from './components/UserLoggedIn'

266
Awesome React.js
import GuestLoggedIn from './components/GuestLoggedIn'
class App extends Component{
constructor(props) {
super(props)
this.state = {
isLoggedIn : true
}
}
render(){
return (
this.state.isLoggedIn ? <UserLoggedIn/> : <GuestLoggedIn />
);
}
}
export default App;
On execution of the above application the following output is generated:

App.js

import React, { Component } from 'react';

267
Awesome React.js
import UserLoggedIn from './components/UserLoggedIn'
import GuestLoggedIn from './components/GuestLoggedIn'
class App extends Component{
constructor(props) {
super(props)
this.state = {
isLoggedIn : false
}
}
toggleLoggedIn = () => {
this.setState({
isLoggedIn:!this.state.isLoggedIn
})
}
render(){
return (
<div>
<div>
Logged In : <input type="checkbox"
onChange={this.toggleLoggedIn.bind(this)}></input>
</div>
<div>
{ this.state.isLoggedIn ? <UserLoggedIn/> : <GuestLoggedIn />}
</div>
</div>
);
}
}
export default App;
On execution of the above application the following output is generated:

268
Awesome React.js

Using switch..case Statement

App.js

import React, { Component } from 'react';
import UserLoggedIn from './components/UserLoggedIn'
import GuestLoggedIn from './components/GuestLoggedIn'
class App extends Component{
constructor(props) {
super(props)
this.state = {
isLoggedIn : true
}
}
toggleLoggedIn = () => {
this.setState({
isLoggedIn:!this.state.isLoggedIn

269
Awesome React.js
})
}
render(){
switch(this.state.isLoggedIn) {
case true:
return <UserLoggedIn/>;
case false:
return <GuestLoggedIn/>;
default:
return null;
}
}
}
export default App;

App.js

import React, { Component } from 'react';
import UserLoggedIn from './components/UserLoggedIn'
import GuestLoggedIn from './components/GuestLoggedIn'
class App extends Component{
constructor(props) {
super(props)
this.state = {
isLoggedIn : false
}
}
logInOut = () => {
this.setState({
isLoggedIn:!this.state.isLoggedIn
})
}
render(){

270
Awesome React.js
switch(this.state.isLoggedIn) {
case true:
return <div><UserLoggedIn/><button onClick={this.logInOut.bind(this)}>Log
Out</button></div>
case false:
return <div><GuestLoggedIn/><button onClick={this.logInOut.bind(this)}>
Log In</button></div>
default:
return null;
}
}

export default App;

5.13 List Rendering Revisited


The following example demonstrates rendering the elements stored in an array using map()
method.

271
Awesome React.js
CourseList.js

import React from 'react';
function CourseList() {
let courses=['MCA', 'MBA', 'MSW', 'MPhil']
return (
<div>
{
courses.map(name=><div><h2><font color='green'>{name}</font></h2></div>)
}
</div>
);
}
export default CourseList

app.js

import logo from './logo.svg';
import './App.css';
import CourseList from './components/CourseList'
function App() {
return (
<div className="App">
<CourseList/>
</div>
);
}
export default App;

On execution of the above program the following output is generated:

272
Awesome React.js

The following program presents the modified version of the above program where the
properties of the student objects stored as elements of the array are rendered using map()
method.

StudentList.js

import React from 'react';
function StudentList() {
let students=[
{
rollno:1,
name:"Maya"
},
{
rollno:2,
name:"Milan"
},
{
rollno:3,
name:"Ashok"
},
{
rollno:4,
name:"Sachin"
}
]

273
Awesome React.js
let studentList=students.map(student=><div><h2><font color='blue'>My name is
{student.name}
and my rollon is {student.rollno}</font></h2></div>)
return (
<div>
{
studentList
}
</div>
);
}
export default StudentList

app.js

import logo from './logo.svg';
import './App.css';
import StudentList from './components/StudentList'

function App() {
return (
<div className="App">
<StudentList/>
</div>
)
}
export default App;

On execution of the application the following output is generated:

274
Awesome React.js

The following example presents the modified version of the above program where the
functional component ‘Student’ accepts ‘student’ object as a prop, destructures it for
retrieving the ‘name’ and ‘rollno’ properties and returns the JSX to display the corresponding
values.

Student.js

import React from 'react';
function Student({student}) {
return(
<div>
{
<div><h2><font color='maroon'>My name is {student.name} and my rollon is
{student.rollno}</font></h2></div>
}
</div>
)
}
export default Student

Now, the task in the functional component ‘StudentList’ is as simple as passing the ‘student’
object as a prop to the functional component ‘Student’. Creation of JSX is now delegated by
the ‘StudentList’ component to the ‘Student’ component as demonstrated below:

275
Awesome React.js
StudentList.js

import React from 'react';
import Student from './Student';
function StudentList() {
let students=[
{
rollno:1,
name:"Maya"
},
{
rollno:2,
name:"Milan"
},
{
rollno:3,
name:"Ashok"
},
{
rollno:4,
name:"Sachin"
}
]
let studentList=students.map(student=><Student student={student}></Student>)
return (
<div>
{
studentList
}
</div>
);
}
export default StudentList

276
Awesome React.js
On execution of the application the same output as above is generated:

However, on execution of the above application the following warning message is generated:

Adding Keys to List in React.js


For the efficient manipulation of the list React requires a unique key to be added to every
element of a list to identify the element uniquely. This can be achieved using the following
syntax. It assigns the rollno of a student as a key which is considered to be unique.

let studentList=students.map(student=><Student key={student.rollno}


student={student}></Student>)
With the above change in place, same output as above is generated. Key should be unique
within the list.
student.js

import React from 'react';
function Student({student,key}) {
return(
<div>

277
Awesome React.js
{
<div><h2><font color='maroon'>{key} My name is {student.name} and my rollon is
{student.rollno}</font></h2></div>
}
</div>
)
}
export default Student

Keys in a List
A key is a special string attribute required to identify the list elements uniquely. Keys help
React identify which items have undergone a change, are newly inserted or removed from the
list. Keys provide smooth and efficient update of the user interface when the rendered list
undergoes changes.

Handling Lists Without Unique Attributes


Using index as Keys in Rendering List
app.js

import logo from './logo.svg';
import './App.css';
import CourseList from './components/CourseList'

function App() {
return (
<div className="App">
<CourseList/>
</div>
)
}
export default App;

278
Awesome React.js
On execution of the above application the following warning message is generated:

To get rid of the above warning message add index as key while rendering the elements of a
list as shown in the following program:
CourseList.js

import React from 'react';
function CourseList() {
let courses=['MCA', 'MBA', 'MSW', 'MPhil']
let courseList=courses.map((name,index)=><div key={index}><h2 ><font
color='blue'>{index}
{name}</font></h2></div>)
return (
<div>
{
courseList
}
</div>
);
}
export default CourseList

On execution of the above program the following output is generated:

279
Awesome React.js

When to Use Index as a Key?


The criteria deciding using index as a key are listed below:
● When the list is static and will not change.
● The list is never sorted or reordered or filtered.
● The items in the list do not possess a unique id.

280
Awesome React.js

Chapter 6
Styling React Components
6.1 Adding Style to React Components
The different methods for adding style to the React components are listed below:
● CSS Stylesheets
● Inline styling
● CSS Modules
● CSS in JS Libraries

The following application uses the style stored in external stylesheet with the name
‘styles.css’ and applies the style to the <h1> element.
styles.css

.maroon {
color: maroon
}

Stylesheet.js

import React from 'react';
import './styles.css'

function Stylesheet(props) {
return (
<div>
<h1 className="maroon">Exploring Stylesheets in React.js</h1>
</div>
);
}
export default Stylesheet;

281
Awesome React.js
app.js

import logo from './logo.svg';
import './App.css';
import Stylesheet from './components/Stylesheet'
function App() {
return (
<div className="App">
<Stylesheet/>
</div>
)
}
export default App;

On execution of the program, the following output is generated:

6.2 Conditionally Applying the Styles


In the given example, JSX follows the convention of camel-case notation for attribute names.
The variable 'className' is assigned a value of either 'red' or 'maroon' based on the 'isError'
property passed as a prop to the functional component 'Stylesheet'. This 'className' value is
then assigned to the 'className' attribute of the <h1> element. The purpose of this approach
is to conditionally apply different CSS classes to the <h1> element based on the value of the
'isError' prop.
styles.css

.maroon {
color: maroon

282
Awesome React.js
}
.red{
color:red
}

Stylesheet.js

import React from 'react';
import './styles.css'
function Stylesheet(props) {
let className=props.isError? 'red' : 'maroon'
return (
<div>
<h1 className={className}>Exploring Stylesheets in React.js</h1>
</div>
);
}
export default Stylesheet;

app.js

import logo from './logo.svg';
import './App.css';
import Stylesheet from './components/Stylesheet'
function App() {
return (
<div className="App">
<Stylesheet isError={false}/>
</div>
)
}
export default App;

283
Awesome React.js
On execution of the above application the following output is generated:

Change the value of ‘isError’ prop to ‘true’ as shown below and re-execute the application.
app.js

import logo from './logo.svg';
import './App.css';
import Stylesheet from './components/Stylesheet'

function App() {
return (
<div className="App">
<Stylesheet isError={true}/>
</div>
)
}
export default App;
On execution of the application the following output is generated:

6.3 Applying Multiple Styles


In the provided example, multiple styles can be applied to a single element by specifying the
style names as a space-separated list. The styles 'large' and 'maroon' are applied to the <h1>

284
Awesome React.js
element using a string literal within back ticks. The expression ${className} inside the back
ticks allows the value stored in the variable 'className' to be interpolated based on the
'isError' prop. This enables dynamic styling of the <h1> element based on the condition
specified by the 'isError' prop.
styles.css

.maroon {
color: maroon
}
.red{
color:red
}
.large{
font-size: 64px;
}

Stylesheet.js

import React from 'react';
import './styles.css'
function Stylesheet(props) {
let className=props.isError? 'red' : 'maroon'
return (
<div>
<h1 className={`${className} large`}>Exploring Stylesheets in React.js</h1>
</div>
);
}
export default Stylesheet;
App.js

function App() {
return (

285
Awesome React.js
<div className="App">
<Stylesheet isError={false}/>
</div>
)
}
export default App;

On execution of the application the following output is generated:

6.4 Applying Inline Styles


In React, you can apply inline styles to components using the 'style' attribute. The 'style'
attribute accepts an object where each key represents a CSS property, and the corresponding
value represents the value of that property. This allows for dynamic styling of components by
defining the styles directly within the JSX code. The following example demonstrates the
usage of inline styles in React.js.
Style1.js

import React from 'react';
import './styles.css'
const headingStyle={
fontSize:'64px',
color: 'green',
fontStyle:'italic'
}
function Stylesheet1(props) {
return (
<div>

286
Awesome React.js
<h1 style={headingStyle}>Exploring Stylesheets in React.js</h1>
</div>
);
}
export default Stylesheet1;

In the above example, the headingStyle object defines the inline styles for the <h1>
component. The color, fontSize, and fontStyle properties are set to 'green', '64px', and 'italic',
respectively. The style attribute is then used on the <h1> element with the headingStyle
object.

App.js

import logo from './logo.svg';
import './App.css';
import Stylesheet1 from './components/Stylesheet1'

function App() {
return (
<div className="App">
<Stylesheet1/>
</div>
)
}
export default App;

On execution of the application the following output is generated:

287
Awesome React.js
JavaScript expressions can be employed within the inline styles to make them dynamic as
demonstrated in the following program:

MyComponent.js

import React from 'react';
const MyComponent = () => {
const textColor = 'orange';
const fontSize = 24;
const divStyle = {
color: textColor,
fontSize: `${fontSize}px`,
fontWeight: 'bold'
};
return (
<div style={divStyle}>
This is an Example of Dynamically-Styled Text.
</div>
);
};
export default MyComponent;
On execution of the above program the following output is generated:

In this updated example, the textColor and fontSize variables are used within the divStyle
object to apply dynamic values to the color and fontSize properties, respectively.

288
Awesome React.js
Note: The property names in the style object follow the camelCase convention instead of the
hyphenated CSS syntax. For example, background-color becomes backgroundColor, and
font-size becomes fontSize.

6.5 Exploring CSS Modules


CSS Modules is a widely adopted technique in React.js applications for organizing and
modularizing CSS styles. It enables developers to write CSS styles that are scoped to specific
components, preventing global class name conflicts and promoting improved encapsulation.
Using CSS Modules, you can create a dedicated CSS file that is specifically associated with a
particular component, rather than having a generic style file. The class names defined within
this file are locally scoped to that component, ensuring they won't clash with class names
used in other components.

By leveraging CSS Modules, developers can enjoy the benefits of encapsulation, making it
easier to manage and maintain CSS styles within their React.js applications.
The following example demonstrates using CSS Modules in a React component:

Step 1:
In ‘src’ folder create a CSS file with the name ‘styles.module.css’ and insert the following
content in it:

styles.module.css

.myComponent {
color: maroon;
font-size: 48px;
}

Step 2:
In the React component file, import the CSS module and apply the styles using the imported
class names

289
Awesome React.js
In ‘src’ folder create a file with the name ‘MyComponent.js’ and insert the following code in
it.
MyComponent.js

import React from 'react';
import styles from './styles.module.css';

const MyComponent = () => {


return (
<div className={styles.myComponent}>
This is a Component with Scoped Styles.
</div>
);
};
export default MyComponent;

App.js

import './App.css';
import MyComponent from './components/MyComponent';
function App() {
return (
<div className="App">
<MyComponent/>
</div>
);
}
export default App;
On execution of the above program the following output is generated:

290
Awesome React.js

In this example, the styles object is imported from the CSS module file. The myComponent
class name is accessed from the styles object and applied to the className attribute of the
<div> element. The styles defined in the CSS module will be scoped to this specific
component.

Under the hood, CSS Modules generates unique class names for each component, ensuring
that the styles are isolated and won't conflict with other components.
Using CSS Modules helps improve the maintainability and reusability of CSS styles in a
React application by providing clear separation and encapsulation of styles within individual
components.

It's worth noting that CSS Modules are just one approach to managing styles in React. Other
popular options include CSS-in-JS libraries like styled-components, or using CSS
preprocessors like Sass or Less.

Example:
The following program demonstrates yet another example for using CSS modules. The
‘orangelarge’ style from the CSS module is applied to the style component.

styleModule,js

import React from 'react';
import styles from '../styles.module.css'

function Stylesheet1(props) {
return (
<div>

291
Awesome React.js
<h1 className={styles.orangelarge}>Exploring Stylesheets in React.js</h1>
</div>
);
}
export default Stylesheet1;

styles.module.css

.orangelarge{
color:orange;
font-size: 72px
}

App.js

import logo from './logo.svg';
import './App.css';
import Stylesheet1 from './components/Stylesheet1'
function App() {
return (
<div className="App">
<Stylesheet1/>
</div>
)
}
export default App;

On execution of the application the following output is generated:

292
Awesome React.js
Advantages Offered by CSS Modules
CSS modules are locally scoped in contrast to traditional CSS which is globally scoped.

Using both Inline Style Sheets and CSS Modules in a Single Program
In the following program both the inline stylesheet and CSS module to level1 heading. This is
possible since CSS modules are local to the component.

Styles.module.css

.myComponent {
color: maroon;
font-size: 48px;
}
StyleSheet1.js

import React from 'react';
import './styles.css'
import styles from './styles.module.css';
const headingStyle={
fontSize:'48px',
color: 'green',
fontStyle:'italic'
}
function Stylesheet1(props) {
return (
<div>
<div>
<h1 style={headingStyle}>This is a Component with Inline Style</h1>
</div>
<div className={styles.myComponent}>
This is a Component with Scoped Style
</div>
</div>

293
Awesome React.js
);
}
export default Stylesheet1;

App.js

import './App.css';
import StyleSheet1 from './components/Stylesheet1';
function App() {
return (
<div className="App">
<StyleSheet1/>
</div>
);
}
export default App;
On execution of the above program the following output is generated:

294
Awesome React.js

Chapter 7
Exploring React Form
7.1 Types of Controls in React
There are mainly two types of controls in React:
● Uncontrolled Components
● Controlled Components
An uncontrolled component in React is comparable to a traditional form control. In
uncontrolled components, the DOM elements themselves handle and update their own state
when the input value changes. To implement an uncontrolled component, the 'ref' keyword is
used to obtain a reference to the underlying DOM element. With uncontrolled components,
there is no requirement to implement an event handler for every state update, as the DOM
handles the state internally.

Creating a Reference
A reference is created using the createRef() method of React class as shown below:
this.name = React.createRef()
App.js

import React, { Component } from 'react';
import FirstComponent from './components/FirstComponent';
import SecondComponent from './components/SecondComponent';
class App extends Component{
constructor(props) {
super(props)
this.name = React.createRef()
this.submitData = this.submitData.bind(this)
}
submitData(event) {
alert(`Name : ${this.name.current.value}`);
event.preventDefault();
}

295
Awesome React.js
render(){
return (
<div>
<form onSubmit={this.submitData}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.name}/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;
On execution of the above application the following output is generated:

296
Awesome React.js
7.1.1 Uncontrolled Components
In uncontrolled components, the state of a component is managed by the DOM rather than
being controlled by React component state. React doesn't have direct control or knowledge of
the uncontrolled component's state, and the data is managed directly by the HTML elements
themselves. To create an uncontrolled component, you don't need to write an event handler
for every state update. Instead, you can use a ref to access the value of the form directly from
the DOM. This approach can be useful in certain scenarios where you want to leverage the
native behavior of HTML elements without the need for explicit state management in React.

Key Characteristics of Uncontrolled Components


Few prominent characteristics of uncontrolled components are listed below:

No explicit state management:


In uncontrolled components the data is stored and managed within the DOM itself and it is
not required to define the state variables or event handler for the management of component’s
data.
Direct interaction with the DOM
The traditional JavaScript methods such as getElementById() querySelector() can be
employed for accessing and manipulating the component’s data by accessing directly the
‘value’ property of the control. Uncontrolled components enable direct interaction with the
DOM elements using these traditional JavaScript methods.
Refs for accessing DOM elements
A reference to the DOM element can be created using React’s ‘ref’ feature which enables
interaction with the uncontrolled components. This reference can then be employed for
accessing and modifying the DOM element directly.

Suitable for simple forms or inputs


Uncontrolled components are often used in the situation where there is no need for explicit
state management such as simple forms or inputs where you don't need to perform extensive
validation or complex state manipulation. They provide a straightforward way to handle basic
user input without the need for explicit state management.

297
Awesome React.js
Working of Uncontrolled Components

In the above figure:


 ‘nameref ‘ is a reference to the input element.
 When the text in the input element changes, handleSubmit() event handler is invoked.
 handleSubmit() event handler retrieves the current value of input control using the
statement, this.nameref.current.value which is used for updating the state.
 On state updation the component is re-rendered and the new state value is displayed in
input control.

Code Snippet for Using Uncontrolled Component in React


UncontrolledComponent.js

import React from 'react'
class UncontrolledComponent extends React.Component {
handleSubmit = (event) => {
event.preventDefault();
const name = this.name.value;
console.log(name)
}

298
Awesome React.js
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={ref => this.name = ref} />
<button type="submit">Submit</button>
</form>
);
}
}
export default UncontrolledComponent

App.js

import './App.css';
import UncontrolledComponent from './components/UncontrolledComponent';
function App() {
return (
<div className="App">
<UncontrolledComponent/>
</div>
);
}
export default App;

On execution of the above application the following output is generated:

On clicking the ‘Submit’ button the name is displayed in the console as shown below:

299
Awesome React.js

In the example above, the input element is an uncontrolled component because React is not
managing its value. The value entered by the user can be accessed directly using the ref
created with this.inputRef. When the form is submitted, the handleSubmit method retrieves
the value and performs further processing as needed.
Alternatively the reference can be defined as a class variable and can be accessed from
HTML element as demonstrated in the following program:
Uncontrolled.js

import React from 'react'
class UncontrolledComponent extends React.Component {
nameref=React.createRef(null)
handleSubmit = (event) => {
event.preventDefault();
const name = this.nameref.current.value;
console.log(name)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.nameref} />
<button type="submit">Submit</button>
</form>
);
}
}
export default UncontrolledComponent
On execution of the above program the following output is generated:

300
Awesome React.js

Uncontrolled components can be useful in certain scenarios where a simpler and less state-
driven approach is preferred. However, controlled components, where the component state is
controlled and managed by React, offer more control and flexibility, especially for complex
forms or when more advanced data validation and manipulation are required.

7.1.2 Controlled Components


In a controlled component, the state is bound to a value and any changes to that value are
handled through event-based callbacks. React takes full control and management of the
component's state in controlled components. The state is assigned to a mutable property and
can only be updated using the setState() method in response to state updates.

In a controlled component, the current value is passed through props and any changes to the
value are notified through callbacks, such as the 'onChange' event. The parent component
handles these callbacks, manages its own state, and then passes the updated values as props to
the controlled component. This allows React to control and synchronize the component's state
with the user's input or other interactions, ensuring consistency and enabling powerful data
manipulation and validation.

Key Characteristics of Controlled Components


Here are the few key characteristics of controlled components:
State managed by React
In controlled components, the component's state is defined and managed using React's state
variables. The state variables hold the data and define the behaviour of the component.

301
Awesome React.js

Event handlers for data updates


Controlled components are bound to a value and its changes will be handled in code by using
event-based callbacks. To update the component's state and handle user interactions, event
handlers are defined and associated with the appropriate DOM events (such as onChange for
input elements). Camel case notation is used for specifying the event handler. These event
handlers modify the component's state using the setState() function.

Component re-rendering
As the component state is updated, React triggers a re-render of the component, reflecting the
updated state in the UI. This ensures that the UI always stays in sync with the component's
state.

Data Flow in controlled Component


● The data flow in controlled component is enumerated below:
● The user enters a text in a controlled component.
● A DOM event is generated and the corresponding event handler is executed.
● The event handler updates the state of the component using setState() method.
● The change in component’s state triggers render() method for synchronizing UI with
corresponding state updation.

Code Snippet for Using Controlled Component


ControlledComponent.js

import React from 'react'
class ControlledComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ''
};
}
handleChange = (event) => {
console.log("Inside handleChange")

302
Awesome React.js
this.setState({ name: event.target.value });
}
handleSubmit = (event) => {
console.log("Inside handleSubmit")
event.preventDefault();
const { name } = this.state;
console.log(name)
}
render() {
console.log("Inside render")
const { name } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={name} onChange={this.handleChange} />
<button type="submit">Submit</button>
</form>
);
}
}
export default ControlledComponent

App.js

import './App.css';
import ControlledComponent from './components/ControlledComponent';
function App() {
return (
<div className="App">
<ControlledComponent/>
</div>
);
}
export default App;

303
Awesome React.js
On execution of the above application the following output is generated:

Following messages are logged to the console.

In this example, the input element is implemented as a controlled component in React. This
means that the value of the input is controlled and managed by React's component state,
specifically the 'name' state variable.

The value prop of the input element is set to the 'name' state variable, ensuring that the input
always displays the current value stored in the state. Any changes made to the input by the
user trigger the 'handleChange' method, which updates the 'name' state with the new value
entered by the user.

By keeping the input value synchronized with the component's state, React ensures that the
component remains the single source of truth for the input value. This allows for easier
manipulation, validation, and consistency of the data.

304
Awesome React.js
When the form is submitted, the 'handleSubmit' method retrieves the value stored in the
'name' state for further processing, such as submitting it to a server or updating other
components with the latest data. This way, the controlled component pattern in React
provides a predictable and reliable way to manage and interact with user input.

Controlled components offer a higher level of control and flexibility in comparison to


uncontrolled components. They prove to be particularly valuable when dealing with intricate
forms, implementing validation logic, and performing data manipulations before submitting
or displaying it. By utilizing controlled components, React gains a comprehensive
understanding of the component's state, leading to easier debugging and more straightforward
testing processes.

By maintaining control over the component's state, React can orchestrate and synchronize the
flow of data, ensuring consistency and accuracy throughout the application. This level of
control allows for seamless integration with validation libraries, enables real-time updates
and feedback to the user, and facilitates seamless interactions with the form data.

Additionally, controlled components offer increased transparency and maintainability in


complex form scenarios. They provide a clear data flow path, making it easier to track and
manage changes, implement business logic, and propagate updates to other components when
necessary.

Overall, the use of controlled components empowers developers to have fine-grained control
over the state and behavior of their forms, promoting robustness, maintainability, and a better
user experience.

The different steps involved in using the controlled component are enumerated below:
1. Define State
2. Add a change handler to handle the state mutation and update the state using
setState() method.
3. Handle form submission.

Modify the ‘render’ method as shown below:


render() {
console.log("Inside render")
const { name } = this.state;

305
Awesome React.js
return (
<form onSubmit={this.handleSubmit}>
<h4>Name : {this.state.name}</h4>
<input type="text" value={name} onChange={this.handleChange} />
<button type="submit">Submit</button>
</form>
);
}

and re-execute the program. The following output is generated.

render() method is invoked several times to update UI inline with state updation (name).
The following example demonstrates using uncontrolled component in a React application.

306
Awesome React.js
App.js

import React, { Component } from 'react';
class App extends Component{
constructor(props) {
super(props)
this.state = {
name : ""
}
this.submitData = this.submitData.bind(this)
}
submitData(event) {
alert(`Name : ${this.state.name}`);
event.preventDefault();
}
changeHandler = (event) => {
this.setState({name : event.target.value})
}
render(){
return (
<div>
<form onSubmit={this.submitData}>
<h1>Controlled Form Example</h1>
<label>Name:
<input type="text" onChange={this.changeHandler}/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;

307
Awesome React.js
On execution of the application the following output is generated:

7.1.3 Differences Between Controlled and Uncontrolled component

The difference between controlled and uncontrolled components in React is decided by to


how the component's state is managed and updated.

Following table summarizes the salient differences between controlled and uncontrolled
components in React.js
Controlled Component Uncontrolled Component
State is controlled by the parent component. State is controlled and managed by DOM
without explicit control from React or the
component itself.
The current value can be accessed using prop ‘ref’ is used for directly accessing and
and notify changes to the component through modifying the current DOM element’s value.
event callbacks. The component’s state is
updated via state updates so that the
component is always in synch with current
state value.
It is suitable for complex forms and has It is suitable for simple forms and has limited
better control over the form elements. control over form elements.
State is managed by React. The component’s The component’s value is directly accessed
state is controlled by component itself and from DOM element and changes are not
any changes to the state are handled through managed through state updates.
event callbacks.
<input> element contains ‘value’ prop. <input> element does not contain ‘value’
prop instead has a ‘ref’ attribute.
Controlled components allow for easier Uncontrolled components may require

308
Awesome React.js
validation and error handling as all updates additional effort to validate and handle errors
are controlled and managed through React due to direct DOM access.

To summarize, the choice between controlled and uncontrolled components depends on the
specific requirements and complexity of your application. Controlled components provide
more control and flexibility, but may require more code and state management, while
uncontrolled components can be simpler but may lack the full control and benefits of React's
state management.

7.2 Basics of Form Handling in React.js


Controlled Components in React.js

In the above figure:


 ‘name’ is a state variable whose initial value is displayed in input control.
 When the user modifies the name displayed in the input control change event is
triggered which invokes the event handler changeHandler()
 Inside changeHandler() the state is updated asynchronously using setState() method.
 Change in state triggers re-render of input control with the new value of state.
The following program demonstrates creating a controlled component in React.js.
MyForm.js

import React, { Component } from 'react';
class MyForm extends Component {

309
Awesome React.js
constructor(props){
super(props)
this.state={
name:''
}
}
changeName = (event) =>{
this.setState({
name: event.target.value
}
)
}
render() {
return (
<form>
<div>
<label>Name : </label>
<input type='text' value={this.state.name}
onChange={this.changeName}></input>
</div>
</form>
);

}
}
export default MyForm;

App.js

import logo from './logo.svg';
import './App.css';
import MyForm from './components/MyForm'
function App() {

310
Awesome React.js
return (
<div className="App">
<MyForm/>
</div>
)
}
export default App;

On execution of the above application the following output is generated:

7.3 Submitting Form Data


The following program demonstrating submitting the form data on clicking the ‘Submit’
button.

MyForm.js

import React, { Component } from 'react';
class MyForm extends Component {
constructor(props){
super(props)
this.state={
name:''
}
}
changeName = (event) =>{
this.setState({
name: event.target.value
}

311
Awesome React.js
)
}
submit = (event) =>{
alert(`${this.state.name}`)
event.preventDefault()
}
render() {
return (
<form onSubmit={this.submit}>
<div>
<label>Name : </label>
<input type='text' value={this.state.name}
onChange={this.changeName}></input>
</div><br></br>
<div>
<button type='submit'>Submit</button>
</div>
</form>
);
}
}
export default MyForm;

On execution of the program the following output is generated:

312
Awesome React.js

refs in React
In React, both ref and callback ref are used to reference and interact with DOM elements or
React components. However, there are some differences between them in terms of how they
are implemented and how they are used.

ref
The ref is an attribute in React that allows you to create a reference to a React component or a
DOM element. It can be used in two different ways:

String Refs
In older versions of React, you could pass a string as a ref to a DOM element and later access
it using this.refs. However, this approach is considered legacy and is not recommended in
newer versions of React.

Callback Refs

313
Awesome React.js
In the current versions of React, you can use a callback function to create a ref. The callback
function receives the actual DOM element or the mounted instance of the React component
as its argument. You can then store this reference in a class property or a state variable for
later use.

Callback refs
A callback ref is an alternative approach to using the ref attribute in React. Instead of directly
assigning the ref to a component or element, you pass a callback function as the value of the
ref attribute. This callback function gets called with the actual DOM element or React
component instance when it gets mounted or unmounted.

In React, there exists an alternative approach to using refs known as ‘callback refs’, which
provides greater control over when the refs are set and unset. Instead of employing the
traditional createRef() method to create refs, React offers a means to generate refs by
utilizing a callback function passed to the ref attribute of a component. This technique
empowers developers with enhanced flexibility in managing the lifecycle of refs. By
leveraging this methodology, you can finely tune the behavior of your components and
ensure efficient handling of references within your React application.
<input type="text" ref={element => this.callRefInput = element} />

The above code snippet demonstrates the usage of callback refs in React.
In this particular example, an <input> element is being rendered within a React component.
The ‘ref’ attribute is set to a callback function
element => this.callRefInput = element.
When the component is rendered, this callback function is executed, receiving the reference
to the underlying DOM node of the <input> element as its argument. In this case, the
argument is assigned the name ‘element’.

Inside the callback function, this.callRefInput = element assigns the received element to a
property called callRefInput of the component's instance. This means that this.callRefInput
will now hold a reference to the underlying DOM node of the <input> element.

314
Awesome React.js
By using this callback ref approach, you have the flexibility to perform custom operations or
store the reference in a way that suits your needs. You can access and manipulate the input
element's properties, invoke methods, or attach event listeners using this stored reference.
The callback function is used to store a reference to the DOM node in an instance property
and can be accessed elsewhere. It can be accessed as shown below:
this.callRefInput.value

Exploring Callback Refs


There are four simple steps in using Callback Refs.
Step 1: Creating a ref property
this.ref=null

Step 2: Assigning a DOM element to the cbRef created above


setRef = (element) => {
this.ref = element;
};

Step 3: Attaching a callback ref to the input element


<input type="text" ref={this.setRef} />
The input element is implicitly passed as a parameter which is assigned to the callback ref.

Step 4:
React will call the ref callback with the DOM element when the component mounts and call
it with null when the component unmounts.

Here's an example of using a callback ref in a class component:


MyComponent.js

import React from "react";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.ref = null;

315
Awesome React.js
}
setRef = (element) => {
this.ref = element;
};
handleClick = () => {
if (this.ref) {
// Access the DOM element or component instance using the ref
console.log(this.ref.value);
}
};
render() {
return (
<div>
<input type="text" ref={this.setRef} />
<button onClick={this.handleClick}>Display</button>
</div>
);
}
}
export default MyComponent

App.js

import React from 'react';
import MyComponent from './components/MyComponent';
const App = () => {
return (
<div>
<h1><font color='maroon'>Callback Ref Demo</font></h1>
<MyComponent />
</div>
);
};

316
Awesome React.js
export default App;
On execution of the above application the following output is generated:

In this example, the setRef method is passed as a callback to the ref attribute, and it sets the
this.ref property to the actual DOM element or React component instance.

Here's an example of using a callback ref in a functional component:


import React, { useRef } from 'react';
const MyComponent = () => {
const ref = useRef(null);
const handleClick = () => {
// Access the DOM element using the ref
console.log(ref.current.value);
};
return (
<div>

317
Awesome React.js
<input type="text" ref={ref} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
Callback Ref:

To summarize, the key difference between ref and callback ref lies in their syntax and
implementation style. The ref attribute with a callback function is the recommended approach
in modern React for creating references to DOM elements or components. The older string-
based ref approach is considered legacy and discouraged in ref and callback ref.

Relative Comparison Between Ref and Callback Ref


Following table summarizes the prominent differences between Ref and Callback Ref
Ref Callback Ref
The ref property is created using The ref property is declared and then
React.createRef() method assigned a value using the method which
const ref=React.createRef() assigns a DOM element to the property.
this.ref = null;
setRef = (element) => {
this.ref = element;
};

The ref property created above is assigned to The callback method is assigned to ‘ref’
‘ref’ attribute of input element attribute of input element
<input type="text" ref={ref} /> <input type="text" ref={this.setRef} />
The input element is accessed using the The input element is accessed directly using
following syntax: the following syntax:
ref.current.value ref.value

318
Awesome React.js
Forwarding Ref from one component to another component
Ref forwarding is a powerful technique employed in React to pass a ref from a parent
component through an intermediary component to one of its child components. This
technique is facilitated by utilizing the React.forwardRef() method.

Ref forwarding becomes particularly valuable when working with higher-order components
or when developing reusable component libraries. It enables the parent component to
maintain control over the ref, even when it needs to be accessed by a specific child
component deep within the component hierarchy.

By employing React.forwardRef(), you can create a new component that accepts a ref as a
parameter and passes it down to a designated child component. This mechanism allows you
to maintain the integrity of the ref's functionality and access it as needed within the child
component.

Overall, ref forwarding provides an elegant solution for managing and manipulating refs in
complex component structures, empowering developers to create more flexible and reusable
React components.

Step 1: Create a ref in parent component

Step 2: Attach the ref to the child component using ref attribute.

Step 3: Forward the ref to the input element in the child component using the forwardRef()
method from the React library which takes component as a parameter.
forwardRef() method accepts two parameters:
 First parameter is ‘props’
 Second parameter is ‘ref’
‘ref’ attribute can be used for assigning a value to the ref attribute of native element.
Ref is forwarded from the parent component to the child component.

Step 4: Define the click handler for the button in the parent component,
Child component forwards the reference to the parent component.

319
Awesome React.js
The parent component can directly access the input element of a child component using the
following syntax:
this.inputRef.current
On clicking the button the input element gets the focus.

Example:
ParentComponent.js

import React, { Component } from 'react';
import ChildComponent from './ChildComponent'
import { render } from 'react-dom';
class ParentComponent extends React.Component {
constructor(props) {
super(props)
this.inputRef=React.createRef()

}
handleSubmit = e => {
e.preventDefault();
console.log(this.inputRef.current.value);
};
render() {
return (
<div>
<form onSubmit={e => this.handleSubmit(e)}>
<ChildComponent ref={this.inputRef} />
<button>Submit</button>
</form>
</div>
);
}
}
export default ParentComponent;

320
Awesome React.js
ChildComponent.js

import React from 'react';
const ChildComponent = React.forwardRef((props, ref) => {
return(
<div>
<h1><font color='blue'>Forwarding Refs Demo</font></h1>
<input type="text" placeholder="Hello World" ref={ref} /> <br></br><br></br>
</div>
)
})
export default ChildComponent;

App.js

import React from 'react';
import ParentComponent from './components/ParentComponent';
class App extends React.Component {
render() {
return (
<div>
<ParentComponent/>
</div>
);
}
}
export default App;

On execution of the above application the following output is generated:

321
Awesome React.js

On entering a text in an input control and clicking on ‘Submit’ button the text is displayed in
the console as shown in the following figure:

The above code showcases the usage of ref forwarding in React.

Code Explanation
The necessary imports are made from the 'react' and 'react-dom' libraries.
import React, { Component } from 'react';
import { render } from 'react-dom';
The TextInput component is created using the React.forwardRef() method. This component
renders an <input> element with a placeholder text and accepts the ref parameter using the ref
forwarding technique.
const TextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="Hello World" ref={ref} />
));

A ref is created using React.createRef() and assigned to the inputRef variable.


const inputRef = React.createRef();

322
Awesome React.js

The CustomTextInput component is defined as a class component. It includes a method


called handleSubmit which logs the value of the inputRef when the form is submitted.
class CustomTextInput extends React.Component {
handleSubmit = e => {
e.preventDefault();
console.log(inputRef.current.value);
};

Inside the render() method of CustomTextInput, a form is rendered. The TextInput


component is utilized and the inputRef is passed as the ref prop to it.
render() {
return (
<div>
<form onSubmit={e => this.handleSubmit(e)}>
<TextInput ref={inputRef} />
<button>Submit</button>
</form>
</div>
);
}
In summary, the code demonstrates how to create a reusable TextInput component using ref
forwarding. The CustomTextInput component renders a form containing the TextInput
component, and when the form is submitted, the value of the input is logged to the console.
The ref forwarding technique allows the inputRef to access the underlying DOM node of the
<input> element and retrieve its value.

In the above example, there is a component TextInput that has a child as an input field. Now,
to pass or forward the ref down to the input, first, create a ref and then pass your ref down to
<TextInput ref={inputRef}>. After that, React forwards the ref to the ‘forwardRef’ function
as a second argument. Next, we forward this ref argument down to <input ref={ref}>. Now,
the value of the DOM node can be accessed at inputRef.current.

323
Awesome React.js
References:
1. https://reactjs.org
2. https://www.javatpoint.com/reactjs-tutorial
3. https://www.tutorialspoint.com/reactjs/index.htm
4. https://www.geeksforgeeks.org/reactjs-tutorials/
5. https://www.freecodecamp.org/news/react-tutorial-build-a-project/
6. https://reactbyexample.github.io/
7. https://reactforbeginners.com/
8. https://roadtoreact.com/
9. https://egghead.io/courses/learn-react
10. https://www.taniarascia.com/getting-started-with-react/
11. https://tylermcginnis.com/courses/react-fundamentals/
12. https://reacttraining.com/

324
AUTHOR(S)

Dr Poornima G. Naik bears twenty-two years of Dr. Kavita S. Oza is Associate professor and
teaching and research experience in the field of Head of Department of Computer Science at
Computer Science. She has published more Shivaji University, Kolhapur, Maharashtra. She
than 50 research papers in different national and has a vast experience of 24 years in academics.
international journals and presented more than She has published more than 50 research
15 papers in different international and national articles and has authored 15 books. Her research
conferences. She has authored 34 books on interest is machine learning, NLP and
various cutting edge technologies in information Algorithms. Five research students are awarded
technology. She is the recipient of prestigious PhD under her guidance and four research
Dr. APJ Abdul Kalam Life Time Achievement scholars are pursuing their PhD.
National Award for remarkable achievements in
the field of Teaching, Research & Publications
awarded by International Institute for Social and
Economic Reforms, Bangalore.

©International Institute of Organized Research (I2OR), India

978-81-961331-4-6

View publication stats

You might also like