Awesome React
Awesome React
Awesome React
net/publication/372831147
CITATIONS READS
4 4,247
2 authors:
All content following this page was uploaded by Poornima Naik on 03 August 2023.
By
Dr. Poornima G. Naik
Dr. Kavita S. Oza
Awesome React.js
Awesome React.js
(Unleash the Power of Modern UI
Building)
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.
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.
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.
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.
iv
Awesome React.js
Contents
Chapter Page No.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
React Elements
React element is a JavaScript representation of HTML DOM. React provides an API,
React.createElement to create React Element.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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
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.
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.
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
Switch to the folder containing React project and enter the following command:
npm start
32
Awesome React.js
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
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
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:
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.
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.
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.
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.
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.
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.
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
● 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.
● 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:
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.
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.
48
Awesome React.js
In functional components with hooks, the equivalent of initializing state is done using the
useState hook, like this:
function MyComponent() {
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.
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.
The values of current prop and previous state are logged to the console as shown in the
following figure:
51
Awesome React.js
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.
54
Awesome React.js
55
Awesome React.js
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
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;
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
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.
shouldComponentUpdate(nextProps, nextState)
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.
63
Awesome React.js
64
Awesome React.js
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.
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
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.
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;
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;
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.
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
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:
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
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:
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.
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
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
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.
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>
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>
);
}
90
Awesome React.js
React.createElement('h1', { style: { color: 'red' } }, 'Hello, 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' }}>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'));
93
Awesome React.js
),
React.createElement('li', null, 'Item 4')
)
);
}
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>
<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'));
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.
96
Awesome React.js
// Render the component using ReactDOM.render()
ReactDOM.render(React.createElement(Greeting), document.getElementById('root'));
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.
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:
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
ReactDOM.render
Used to render the element into the container. It expects two parameters -
React Element OR JSX
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.
ReactDOM.render processes JSX or React Elements and emits virtual DOM. The virtual
DOM will be merged and rendered in the container.
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. 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.
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.
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
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.
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:
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.
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:
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>
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.
.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.
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.
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.
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.
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>”
}
}
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:
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
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
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’.
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
124
Awesome React.js
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:
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.
Syntax
Constructor(props){
super(props);
}
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;
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",
}
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)
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.
131
Awesome React.js
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
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;
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;
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:
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;
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.
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.
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;
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"/>
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:
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;
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.
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.
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.
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.
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.
155
Awesome React.js
ParentComponent.js
↓
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [prop, setProp] = useState('Initial Value');
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.
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.
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.
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.
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;
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
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.
By following this recommendation, you can ensure that your React components maintain
optimal performance by minimizing unnecessary function instances and promoting efficient
rendering.
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.
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.
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
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
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.
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.
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.
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;
180
Awesome React.js
On clicking the ‘Click Me’ button, the message ‘true’ is logged to the console.
On execution of the application now, the message ‘false’ is logged to the console as shown in
the following figure:
181
Awesome React.js
182
Awesome React.js
export default MyComponent;
183
Awesome React.js
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
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);
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;
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.
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.
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.
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:
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.
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.
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.
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.
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.
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
203
Awesome React.js
}
export default App;
The context value can be consumed by ComponentC and any component below it in the
component tree.
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:
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;
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:
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.
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.
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.
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.
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.
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 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.
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
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.
Here's an example that demonstrates the potential performance impact when using a regular
function expression for event handling:
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:
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 clicking the button the message ‘Button Clicked…’ is logged to the console.
219
Awesome React.js
when invoking the event handler function. Here's an example that demonstrates the revised
code:
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.
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.
223
Awesome React.js
<EventComponent/>
</div>
);
}
export default App;
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
225
Awesome React.js
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:
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
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.
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.
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.
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.
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.
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:
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:
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.
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.
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>
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 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.
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:
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.
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:
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.
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';
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 = () {
}
250
Awesome React.js
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.
In this case, you can import and use the unnamed component as the default export in a
different module.
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.
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
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.
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.
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.
255
Awesome React.js
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:
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’.
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;
259
Awesome React.js
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;
261
Awesome React.js
with the one shown below
this.state={
isAdmin:false
}
and re-execute the application.
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:
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:
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.
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:
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
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;
}
}
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;
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;
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:
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.
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
279
Awesome React.js
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;
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:
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;
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;
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.
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';
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;
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.
297
Awesome React.js
Working of Uncontrolled Components
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 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.
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.
301
Awesome React.js
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.
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:
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.
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.
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.
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>
);
}
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:
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.
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;
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;
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
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.
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.
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.
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 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;
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:
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} />
));
322
Awesome React.js
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.
978-81-961331-4-6