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

React Basics

handbook for REACT JS

Uploaded by

TEJASHREE S V
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

React Basics

handbook for REACT JS

Uploaded by

TEJASHREE S V
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

1.

React Introduction
ReactJS, also known as React, is a popular JavaScript library for building user
interfaces. It is also referred to as a front-end JavaScript library. It was developed by
Facebook and is widely used for creating dynamic and interactive web applications. In
this article, we’ll explore the key concepts of React.

‍What is React?
React is a JavaScript library for building user interfaces (UIs) on the web. React is a
declarative, component based library that allows developers to build reusable UI
components and It follows the Virtual DOM (Document Object Model) approach,
which optimizes rendering performance by minimizing DOM updates. React is fast and
works well with other tools and libraries.

Prerequisite of React
For learning React first you have a clear understanding of HTML, CSS and JavaScript.
As React is a JavaScript library and uses most of its concept so you really have to
understands the major concepts of it.
 HTML and CSS
 JavaScript and ES6
 JSX (Javascript XML) & Babel
 Node+Npm
 Git and CLI (Command Line Interface).

History of React
 React was invented by Facebook developers who found the traditional DOM
slow. By implementing a virtual DOM, React addressed this issue and gained
popularity rapidly.
 The current stable version of ReactJS is 18.2.0, released on June 14, 2022.
The library continues to evolve, introducing new features with each update.
How does React work?
React operates by creating an in-memory virtual DOM rather than directly
manipulating the browser’s DOM. It performs necessary manipulations within this
virtual representation before applying changes to the actual browser DOM. React is
efficient, altering only what requires modification.

Features of React
React is one of the most demanding JavaScript librarys because it is equipped with a
ton of features which makes it faster and production-ready. Below are the few
features of React.

1. Component-Based Architecture
React provides the feature to break down the UI into smaller, self-contained
components. Each component can have its own state and props.

2. JSX (JavaScript Syntax Extension)


JSX is a syntax extension for JavaScript that allows developers to write HTML-like code
within their JavaScript files. It makes React components more readable and expressive.
3. Virtual DOM
React maintains a lightweight representation of the actual DOM in memory. When
changes occur, React efficiently updates only the necessary parts of the DOM.

4. One-way Data Binding


One-way data binding, the name itself says that it is a one-direction flow. The data in
react flows only in one direction i.e. the data is transferred from top to bottom i.e.
from parent components to child components. The properties(props) in the child
component cannot return the data to its parent component but it can have
communication with the parent components to modify the states according to the
provided inputs.

5. Performance
As we discussed earlier, react uses virtual DOM and updates only the modified parts.
So, this makes the DOM to run faster. DOM executes in memory so we can create
separate components which makes the DOM run faster.
6. Components
React divides the web page into multiple components as it is component-based. Each
component is a part of the UI design which has its own logic and design as shown in
the below image. So the component logic which is written in JavaScript makes it easy
and run faster and can be reusable.

7. Single-Page Applications (SPAs)


React is recommended in creating SPAs, allowing smooth content updates without
page reloads. Its focus on reusable components makes it ideal for real-time
applications.
React JS Lifecycle
Every React Component has a lifecycle of its own, lifecycle of a component can be
defined as the series of methods that are invoked in different stages of the
component’s existence. React automatically calls these methods at different points in
a component’s life cycle. Understanding these phases helps manage state, perform
side effects, and optimize components effectively.

1. Initialization
This is the stage where the component is constructed with the given Props and default
state. This is done in the constructor of a Component Class.

2. Mounting Phase
 Constructor: The constructor method initializes the component. It’s where
you set up initial state and bind event handlers.
 render(): This method returns the JSX representation of the component. It’s
called during initial rendering and subsequent updates.
 componentDidMount(): After the component is inserted into the DOM, this
method is invoked. Use it for side effects like data fetching or setting timers.

3. Updating Phase
 componentDidUpdate(prevProps, prevState): Called after the component
updates due to new props or state changes. Handle side effects here.
 shouldComponentUpdate(nextProps, nextState): Determines if the
component should re-render. Optimize performance by customizing this
method.
 render(): Again, the render() method reflects changes in state or props
during updates.

4. Unmounting Phase
 componentWillUnmount(): Invoked just before the component is removed
from the DOM. Clean up resources (e.g., event listeners, timers).
2.React Environment Setup
Note: Everything is explained in 01_React_TLO_Install_Setup
3.React Fundamentals
Table of Content

1. React JSX
2. ReactJS Babel Introduction
3. ReactJS Virtual DOM
4. React JS React DOM
5. ReactJS Lists
6. React Forms
7. ReactJS Keys
8. ReactJS Refs
9. ReactJS Rendering Elements
10. React Conditional Rendering
3.1.React JSX

React JSX is a syntax extension of JavaScript for writing React Code in a simple way.
Using JSX it is easier to create reusable UI components with fewer lines of code in a
template-type language with the power of JavaScript.

What is JSX ?
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript.
React JSX helps us to write HTML in JavaScript and forms the basis of React
Development. Using JSX is not compulsory but it is highly recommended for
programming in React as it makes the development process easier as the code
becomes easy to write and read.

JSX creates an element in React that gets rendered in the UI. It is transformed into
JavaScript functions by the compiler at runtime. Error handling and warnings become
easier to handle when using JSX

React JSX sample code:

This is called JSX (JavaScript XML), it somewhat looks like HTML and also uses a
JavaScript-like variable but is neither HTML nor JavaScript. With the help of JSX, we
have directly written the HTML syntax in JavaScript.

Why JSX ?
 It is faster than normal JavaScript as it performs optimizations while
translating to regular JavaScript.
 It makes it easier for us to create templates.
 Instead of separating the markup and logic in separate files, React
uses components for this purpose. We will learn about components in detail
in further articles.
 As JSX is an expression, we can use it inside of if statements and for loops,
assign it to variables, accept it as arguments, or return it from functions.
Expressions in JSX
In React we are allowed to use normal JavaScript expressions with JSX. To embed any
JavaScript expression in a piece of code written in JSX we will have to wrap that
expression in curly braces {}. The below example specifies a basic use of JavaScript
Expression in React.

Example 1: This example wraps the JSX code in curly braces

In the above program, we have embedded the javascript expression const name =
“Learner”; in our JSX code. We can use conditional statements instead of if-else
statements in JSX.

Example 2: In this example where conditional expression is embedded in JSX:


In the above example, the variable ‘i’ is checked if for the value 1. As it equals 1 so the
string ‘Hello World!’ is returned to the JSX code. If we modify the value of the
variable ‘i’ then the string ‘False!’ will be returned.

Attributes in JSX
JSX allows us to use attributes with the HTML elements just like we do with normal
HTML. But instead of the normal naming convention of HTML, JSX uses the camelcase
convention for attributes.&

 The change of class attribute to className:The class in HTML


becomes className in JSX. The main reason behind this is that some
attribute names in HTML like ‘class‘ are reserved keywords in JavaScript. So,
in order to avoid this problem, JSX uses the camel case naming convention
for attributes.
 Creation of custom attributes:We can also use custom attributes in JSX. For
custom attributes, the names of such attributes should be prefixed by data-
* attribute.

Example 3: This example has a custom attribute with the <h2> tag and we are using
className attribute instead of class.
Specifying attribute values:
JSX allows us to specify attribute values in two ways:
Wrapping elements or Children in JSX
Consider a situation where you want to render multiple tags at a time. To do this we
need to wrap all of these tags under a parent tag and then render this parent element
to the HTML. All the subtags are called child tags or children of this parent element.

Example: In this example we have wrapped h1, h2, and h3 tags under a single div
element and rendered them to HTML:

Note: JSX will throw an error if the HTML is not correct or if there are multiple child
elements without a parent element.

Comments in JSX:
JSX allows us to use comments as it allows us to use JavaScript expressions. Comments
in JSX begin with /* and ends with */. We can add comments in JSX by wrapping them
in curly braces {} just like we did in the case of expressions. The below example shows
how to add comments in JSX:

Converting HTML to JSX


Let us take the following HTML Code and Convert it into JSX

Rules to Write JSX


 Always return a single Root Element: When there are multiple elements in a
component, and you want to return all of them wrap them inside a single
component.
 Close all the tags: When we write tags in HTML some of them are self-
closing like the <img> tag but JSX requires us to close all of them so image
tag will be represented as <img />
 Use camelCase convention wherever possible: When writing JSX if we want
to give class to a tag, we have to use the className attribute which follows
camelCase convention.

3.2.ReactJS Babel Introduction


Here, we will discuss Babel and why it is one of the most widely used transpilers in the
world.
What is babel?
Babel is a very famous transpiler that basically allows us to use future JavaScript in
today’s browsers. In simple words, it can convert the latest version of JavaScript code
into the one that the browser understands. Transpiler is a tool that is used to convert
source code into another source code that is of the same level. The latest standard
version that JavaScript follows is ES2020 which is not fully supported by all browsers
hence we make use of a tool such as ‘babel’ so that we can convert it into the code
that today’s browser understands.

Using Babel with React


We use Babel with React to transpile the JSX code into simple React functions that can
be understood by browsers. Using this way we can assure that our JSX code can work
in almost any browser. This combination is widely used in modern-day web
development.

In order to manually setup babel in React with webpack follow the below steps.

Step 1: Create the folder where you want the application and navigate to it using the
command:

Step 2: After navigating to the directory type the following command

Make sure this is displayed in the terminal


Step 3: Install the necessary react packages using the following command

Step 4: Install webpack and babel using the command

After following the above steps the dependencies in package.json will look like:
Step 5: Create the files named index.html, App.js, index.js,
webpack.config.js, .babelrc
Step 6: Write the following code in webpack.config.js file

Step 7: Inside the scripts section of package.json file add the following code

Step 8: Add the following code in index.html, index.js, and App.js


Step 9: Inside the .babelrc file add the following code

The package.json should look like:

{
"name": "my-app",
"version": "1.0.0",
"description": "",
Step 9: To run the application, type the following command in a web browser

Output: The output in the browser will look like

Why do we need Babel?


The main reason we need Babel is that it gives us the privilege to make use of the
latest things JavaScript has to offer without worrying about whether it will work in the
browser or not.

Features of Babel:
 Babel-Plugins: The Plugins are configuration details for Babel to transpile
the code that supports a number of plugins, which could be used
individually, provided the environment is known.
 Babel-Presets: Babel presets have a set of plugins that instruct Babel to
transpile in a specific mode. provided the environment is known.
 Babel-Polyfills: During instances when methods and objects, cannot be
transpiled, We can make use of babel-polyfill to facilitate the use of features
in any browser.
 Babel-CLI: The Command-line interface of Babel has a lot of commands
where the code can be easily compiled on the command line. It also has
features like plugins and presets to be used along with the command making
it easy to transpile the code at once.
3.3.ReactJS Virtual DOM
React JS Virtual DOM is an in-memory representation of the DOM. DOM refers to the
Document Object Model that represents the content of XML or HTML documents as a
tree structure so that the programs can be read, accessed and changed in the
document structure, style, and content.

What is DOM?
DOM stands for ‘Document Object Model’. In simple terms, it is a structured
representation of the HTML elements that are present in a webpage or web app. DOM
represents the entire UI of your application. The DOM is represented as a tree data
structure. It contains a node for each UI element present in the web document. It is
very useful as it allows web developers to modify content through JavaScript, also it
being in structured format helps a lot as we can choose specific targets and all the
code becomes much easier to work with.

Disadvantages of real DOM:


Every time the DOM gets updated, the updated element and its children have to be
rendered again to update the UI of our page. For this, each time there is a component
update, the DOM needs to be updated and the UI components have to be re-
rendered.

Example:

When writing the above code in the console or in the JavaScript file, these things
happen:
 The browser parses the HTML to find the node with this id.
 It removes the child element of this specific element.
 Updates the element (DOM) with the ‘updated value’.
 Recalculates the CSS for the parent and child nodes.
 Update the layout.
 Finally, traverse the tree and paint it on the screen(browser) display.
Recalculating the CSS and changing the layouts involves complex algorithms, and they
do affect the performance. So React has a different approach to dealing with this, as it
makes use of something known as Virtual DOM.

Virtual DOM
React uses Virtual DOM exists which is like a lightweight copy of the actual DOM(a
virtual representation of the DOM). So for every object that exists in the original DOM,
there is an object for that in React Virtual DOM. It is exactly the same, but it does not
have the power to directly change the layout of the document.
Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets
drawn on the screen. So each time there is a change in the state of our application, the
virtual DOM gets updated first instead of the real DOM.

How does virtual DOM actually make things faster?


When anything new is added to the application, a virtual DOM is created, and it is
represented as a tree. Each element in the application is a node in this tree. So,
whenever there is a change in the state of any element, a new Virtual DOM tree is
created. This new Virtual DOM tree is then compared with the previous Virtual DOM
tree and make a note of the changes. After this, it finds the best possible ways to make
these changes to the real DOM. Now only the updated elements will get rendered on
the page again.

How virtual DOM Helps React?


In React, everything is treated as a component be it a functional component or class
component. A component can contain a state. Whenever the state of any component
is changed react updates its Virtual DOM tree. Though it may sound like it is ineffective
the cost is not much significant as updating the virtual DOM doesn’t take much time.

React maintains two Virtual DOM at each time, one contains the updated Virtual DOM
and one which is just the pre-update version of this updated Virtual DOM. Now it
compares the pre-update version with the updated Virtual DOM and figures out what
exactly has changed in the DOM like which components have been changed. This
process of comparing the current Virtual DOM tree with the previous one is known
as ‘diffing’. Once React finds out what exactly has changed then it updates those
objects only, on real DOM.
React uses something called batch updates to update the real DOM. It just means that
the changes to the real DOM are sent in batches instead of sending any update for a
single change in the state of a component.

We have seen that the re-rendering of the UI is the most expensive part and React
manages to do this most efficiently by ensuring that the Real DOM receives batch
updates to re-render the UI. This entire process of transforming changes to the real
DOM is called Reconciliation.

This significantly improves the performance and is the main reason why React and its
Virtual DOM are much loved by developers all around.

The diagrammatic image below briefly describes how the virtual DOM works in the
real browser environment.

Virtual DOM Key Concepts :


 Virtual DOM is the virtual representation of Real DOM
 React update the state changes in Virtual DOM first and then it syncs with
Real DOM
 Virtual DOM is just like a blueprint of a machine, can do changes in the
blueprint but those changes will not directly apply to the machine.
 Virtual DOM is a programming concept where a virtual representation of a
UI is kept in memory synced with “Real DOM ” by a library such as
ReactDOM and this process is called reconciliation
 Virtual DOM makes the performance faster, not because the processing
itself is done in less time. The reason is the amount of changed information
– rather than wasting time on updating the entire page, you can dissect it
into small elements and interactions
Differences between Virtual DOM and Real DOM
3.4.ReactJS Lists
React Lists are very useful when it comes to developing the UI of any website. Lists are
mainly used for displaying menus on a website, for example, the navbar menu. In
regular JavaScript, we can use arrays for creating lists.
Let us consider that you have a simple to-do app. You can see a list of tasks you need
to do, like "Buy groceries" or "Walk the dog." You can add new tasks, mark them as
done, or remove them from the list.

Steps to Create and Traverse React JS Lists :


We can create lists in React in a similar manner as we do in regular JavaScript i.e. by
storing the list in an array. In order to traverse a list we will use the map() function.
Step 1: Create a list of elements in React in the form of an array and store it in a
variable. We will render this list as an unordered list element in the browser.
Step 2: We will then traverse the list using the JavaScript map() function and update
elements to be enclosed between <li> </li> elements
Step 3: Finally we will wrap this new list within <ul> </ul> elements and render it to
the DOM.

Example: This example implements a simple list in React.


Rendering lists inside Components
In the above code in React, we directly rendered the list to the DOM. But usually, this
is not a good practice to render lists in React. We already have talked about the uses
of Components and had seen that everything in React is built as individual
components. Consider the example of a Navigation Menu. It is obvious that in any
website the items in a navigation menu are not hard coded. This item is fetched from
the database and then displayed as a list in the browser. So from the component’s
point of view, we can say that we will pass a list to a component using props and then
use this component to render the list to the DOM. We can update the above code in
which we have directly rendered the list to now a component that will accept an array
as props and returns an unordered list.
The above warning message says that each of the list items in our unordered list
should have a unique key. A “key” is a special string attribute you need to include
when creating lists of elements in React. We will discuss about keys in detail in further
articles. For now, let’s just assign a string key to each of our list items in the above
code.
This is the updated code with keys:
Output: In the below-shown output you can see the rendered output is the same but
this time without any warning in the console.

Keys are used in React to identify which items in the list are changed, updated, or
deleted. We will learn about keys in more detail in our ReactJS keys Notes.

3.5.React Forms
Forms in React JS are really important for login, signup, or user interaction to the web
page. In HTML the form data is usually handled by the DOM itself but in the case of
React Forms data is handled by the react components.
React Forms
In React Forms, all the form data is stored in the React’s component state, so it can
handle the form submission and retrieve data that the user entered. To do this we use
controlled components.
React forms are used to interact with the user and provides additional functionality
such as preventing the default behavior of the form which refreshes the browser after
the form is submitted.

Controlled Components
In simple HTML elements like input tags, the value of the input field is changed
whenever the user type. But, In React, whatever the value the user types we save it in
state and pass the same value to the input tag as its value, so here DOM does not
change its value, it is controlled by react state. These are known as Controlled
Components.

This may sound complicated But let’s understand with an example.


Adding Forms in React

Forms in React can be easily added as a simple react element. Here are some examples

React Forms Text Input Example:


This example displays the text input value on the console window when the React
onChange event triggers.
Handling React Forms
In HTML the HTML DOM handles the input data but in react the values are stored in
state variable and form data is handled by the components.

React Form Handling Example:


This example shows updating the value of inputValue each time user changes the
value in the input field by calling the setState() function.

Submitting React Forms


The submit action in react form is done by using the event handler onSubmit which
accepts the submit function.

React Forms Submission Example:


Here we just added the React onSubmit event handler which calls the
function onFormSubmit and it prevents the browser from submitting the form and
reloading the page and changing the input and output value to ‘Hello World!’.

3.6.ReactJS Keys
React JS keys are a way of providing a unique identity to each item while creating the
React JS Lists so that React can identify the element to be processed.
What is a key in React?
A “key” is a special string attribute you need to include when creating lists of elements
in React. Keys are used in React to identify which items in the list are changed,
updated, or deleted.
Keys are used to give an identity to the elements in the lists. It is recommended to use
a string as a key that uniquely identifies the items in the list.

Assigning keys to the list


You can assign the array indexes as keys to the list items. The below example assigns
array indexes as keys to the elements.

Issue with index as keys


Assigning indexes as keys is highly discouraged because if the elements of the arrays
get reordered in the future, then it will get confusing for the developer as the keys for
the elements will also change.

Difference between keys and props in React.


Keys are not the same as props, only the method of assigning “key” to a component is
the same as that of props. Keys are internal to React and cannot be accessed from
inside of the component like props. Therefore, we can use the same value we have
assigned to the Key for any other prop we are passing to the Component.

Using Keys with Components:


Consider a situation where you have created a separate component for list items, and
you are extracting list items from that component. In that case, you will have to assign
keys to the component you are returning from the iterator and not to the list items.
That is you should assign keys to <Component /> and not to <li> A good practice to
avoid mistakes is to keep in mind that anything you are returning from inside of the
map () function is needed to be assigned a key.
Incorrect usage of keys:
Example 1: The below code shows the incorrect usage of keys:

Output: You can see in the below output that the list is rendered successfully but a
warning is thrown to the console that the elements inside the iterator are not assigned
keys. This is because we had not assigned the key to the elements we are returning to
the map() iterator.

Correct usage of keys:


Example 2: The below example shows the correct usage of keys.
Output: In the below-given output you can clearly see that this time the output is
rendered but without any type of warning in the console, it is the correct way to use
React Keys.

Uniqueness of Keys:
We have told many times while discussing keys that keys assigned to the array
elements must be unique. By this, we did not mean that the keys should be globally
unique. All the elements in a particular array should have unique keys. That is, two
different arrays can have the same set of keys.

Example 3: In the below code, we have created two different


arrays menuItems1 and menuItems2. You can see in the below code that the keys for
the first 5 items for both arrays are the same still the code runs successfully without
any warning.
3.7.ReactJS Refs
ReactJS Refs are used to access and modify the DOM elements in the React
Application. It creates a reference to the elements and uses it to modify them.
What is Refs in React?
Refs are a function provided by React to access the DOM element and the React
elements created in components. They are used in cases where we want to change
the value of a child component, without making use of props and state.
They allow us to interact with these elements outside the typical rendering workflow
of React. They have wide functionality as we can use callbacks with them.

Creating refs in React


ReactJS Refs can be created using React.createRef() function and attached to a React
element via the ref attribute.

When a class component is constructed, the Refs are commonly assigned to


an instance property so that they can be referenced in the component.

Accessing Refs in React


In React, when a ref is passed to an element in render using the ref attribute, the
underlying DOM element or React component becomes accessible at the current
property of the ref.

Now, we are going to see how we can use refs in our code which will help you to
understand the use case of refs better.
Example
In this example, we use the target value of event e, for getting the value.
Refs Current Properties
The current property value of refs depends on the ref target. Look at the table below,
to understand the difference.

When to use refs


Using refs provides a lot of benefits, and improves your web development experience.
It is helpful in:
 Helpful when using third-party libraries.
 Helpful in animations.
 Helpful in managing focus, media playback, and text selection.

When not to use refs


 Should not be used with functional components because they don’t have
instances.
 Not to be used on things that can be done declaratively.
 When using a library or framework that provides its methods for managing
such as Redux or MobX.

Conclusion
React refs are useful to interact with the DOM structure of components. They can
directly access and manipulate the DOM elements. This guide teaches the purpose of
refs in React, how to create refs, and how to use refs in React with examples.

3.8.ReactJS Rendering Elements


In this article we will learn about rendering elements in ReactJS, updating the
rendered elements and will also discuss about how efficiently the elements are
rendered.

What are React Elements?


React elements are different from DOM elements as React elements are simple
JavaScript objects and are efficient to create. React elements are the building blocks of
any React app and should not be confused with React components which will be
discussed in further articles.

Rendering an Element in React


In order to render any element into the Browser DOM, we need to have a container or
root DOM element. It is almost a convention to have a div element with the id=”root”
or id=”app” to be used as the root DOM element. Let’s suppose our index.html file has
the following statement inside it.

Now, in order to render a simple React Element to the root node, we must write the
following in the App.js file.

Output

Welcome to Learning React!

Now, you have created your first ever React Element and also have rendered it in
place, but React was not developed to create static pages, the intention of using React
is to create a more logical and active webpage. In order to do so, we will need to
update the elements. This next section will guide us through the same.

Updating an Element in React


React Elements are immutable i.e. once an element is created it is impossible to
update its children or attribute. Thus, in order to update an element, we must use the
render() method several times to update the value over time. Let’s see this as an
example.
Write the following code in App.js file of your project directory.

In the above example, we have created a function showTime() that displays the
current time, and we have set an interval of 1000ms or 1 sec that recalls the function
each second thus updating the time in each call. For simplicity, we have only shown
the timespan of one second in the given image.

React Render Efficiency


React is chosen over the legacy of DOM updates because of its increased efficiency.
React achieves this efficiency by using the virtual DOM and efficient differentiating
algorithm.

In the example of displaying the current time, at each second we call the render
method, and the virtual DOM gets updated and then the differentiator checks for the
particular differences in Browser DOM and the Virtual DOM and then updates only
what is required such as in the given example the time is the only thing that is getting
changed each time not the title “Welcome to Learning React!” thus React only updates
the time itself making it much more efficient than conventional DOM manipulation.

Important Points to Note:


 Calling the render() method multiple times may serve our purpose for this
example, but in general, it is never used instead a stateful component is
used which we will cover in further articles.
 A React Element is almost never used isolated, we can use elements as the
building blocks of creating a component in React. Components will also be
discussed in upcoming articles.

3.9.React Conditional Rendering


React allows us to conditionally render components which means that the developer
can decide which component to render on the screen on on the basis of some
predefined conditions. This is known as conditional rendering.

Implementing Conditional Rendering


There may arise a situation when we want to render something based on some
condition. For example, consider the situation of handling a login/logout button. Both
the buttons have different functions so they will be separate components. Now, the
task is if a user is logged in then we will have to render the Logout component to
display the logout button and if the user is not logged in then we will have to render
the Login component to display the login button.

Conditional rendering in React can be implemented in three ways:


 Using if else Statement
 Using Logical && Operator
 Using ternary operator

Let us now implement conditional rendering in React using the above-mentioned


methods:

1. Conditional Rendering using if-else Statement


We can create two components and create a boolean variable which decides the
element to be rendered on the screen.

if-else Conditional Rendering Syntax:

if-else Statement Example:

Open your react project directory and edit the Index.js file from src folder:

import React from "react";


import ReactDOM from "react-dom";

// Message Component
// Message Component
function Message(props)
{
if (props.isLoggedIn)
return <h1>Welcome User</h1>;
else
return <h1>Please Login</h1>;
}

// Login Component
function Login(props) {
return <button onClick={props.clickFunc}>Login</button>;
Explanation:
In the above output, you can see that on clicking the Login button the message and
button get’s changed and vice versa.

2. Conditional Rendering using logical && operator

We can use the logical && operator along with some condition to decide what will
appear in output based on whether the condition evaluates to true or false. Below is
the syntax of using the logical && operator with conditions:

logical && operator Syntax:

If the condition provided in the above syntax evaluates to True then the elements
right after the && operator will be a part of the output and if the condition evaluates
to false then the code within the curly braces will not appear in the output.
logical && operator Example:

Below example is used to illustrate the above-mentioned approach Open your react
project directory and edit the Index.js file from src folder:

Explanation:
You can clearly see in the above output that as the condition (counter == 5) evaluates
to true so the <h1> element is successfully rendered on the screen.
3. Conditional Rendering using ternary operator
In JavaScript we have a short syntax for writing the if-else conditions due to which the
code becomes shorter and easy to read. If the boolean returns true then the element
on left will be rendered otherwise element on the right will be rendered

Ternary Operator Syntax:

Ternary Operator Example:


We will modify the first approach and render the elements using ternary operator

import React from "react";


import ReactDOM from "react-dom";
// Message Component
function Message(props) {
return props.isLoggedIn ? <h1>Welcome User</h1> : <h1>Please Login</h1>;
}
// Login Component
function Login(props) {
return <button onClick={props.clickFunc}>Login</button>;
}
Output:

Preventing Component from Rendering


It might happen sometimes that we may not want some components to render. To
prevent a component from rendering we will have to return null as its rendering
output. Consider the below example:

Rendering Prevention Example:


Open your react project directory and edit the Index.js file from src folder:
Explanation:
You can clearly see in the above output that the Example component is rendered twice
but the <h1> element is rendered only once as on the second render of
the Example component, null is returned as its rendering output.
4.React Components

1. Code Splitting in React


2. React Components
3. ReactJS | Components - Set 2
4. ReactJS Pure Components
5. ReactJS Functional Components
6. Differences between Functional Components and Class Components
4.1. Code Splitting in React
Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and
Browserify which can create multiple bundles that can be dynamically loaded at
runtime.

As websites grow larger and go deeper into components, it becomes heavier. This is
especially the case when libraries from third parties are included. Code Splitting is a
method that helps to generate bundles that are able to run dynamically. It also helps
to make the code efficient because the bundle contains all required imports and files.

Bundling and its efficiency: Bundling is the method of combining imported files with a
single file. It is done with the help of Webpack, Rollup, and Browserify as they can
create many bundles that can be loaded dynamically at runtime.

With the help of code splitting, ‘lazy load’ can be implemented, which means just using
the code which is currently needed.
 The default way of importing is as follows:

 Using code-splitting this can be done as follows:

As soon as Webpack gets this type of syntax, code-splitting is started automatically.


When using the Create React App, it is already set up and can be used immediately.
The Webpack guide on code splitting should be followed if using Webpack. The
instructions can be found here.

When Babel is being used, it has to be made sure that Babel is not transforming the
import syntax, but can parse it dynamically. This can be done using babel-plugin-
syntax-dynamic-import.
React.lazy and Suspense.

As both React.lazy and Suspense are not available for rendering on the server yet now,
it is recommended to use loadable-components for code-splitting in a server-rendered
app. React.lazy is helpful for rendering dynamic import as a regular component.

Before:

After:

The Bundle will be loaded on its own which contains the Component when this
component is rendered first.
The Lazy component should then be rendered inside Suspense Component which
helps to reflect some fallback content meanwhile the lazy component loads.

The fallback prop can accept any element of React which will be rendered while
waiting for the loading of the Component. The Suspense Component can be placed
anywhere above the lazy component. Moreover, multiple lazy components can be
wrapped with a single Suspense Component.
Error Boundaries

Error Boundaries are React components that help when some modules fail to load due
to any issue, an error will be triggered. These errors can be handled properly and
provide a good experience to the user by the use of a suitable error page.

Route-Based Code Splitting

It can be difficult to implement code-splitting in code, the bundles can be split evenly,
which will improve the experience for the user.
Here you can see the example code for this.
Named Exports

React.lazy currently supports only default exports. An intermediate module that re-
exports as default has to be created if one wants to import a module that uses named
exports. This ensures the working of tree shaking and prevents the pulling in of unused
components.
4.2. React Components
In React, components serve as independent and reusable code blocks for UI elements.

They represent different parts of a web page and contain both structure and behavior.
They are similar to JavaScript functions and make creating and managing complex
user interfaces easier by breaking them down into smaller, reusable pieces.

What are React Components?


A Component is one of the core building blocks of React. They have the same purpose
as JavaScript functions and return HTML. Components make the task of building UI
much easier.

A UI is broken down into multiple individual pieces called components. You can work
on components independently and then merge them all into a parent
component which will be your final UI.

Components promote efficiency and scalability in web development by allowing


developers to compose, combine, and customize them as needed.

You can see in the below image we have broken down the UI of GeeksforGeeks’s
homepage into individual components.

Components in React return a piece of JSX code that tells what should be rendered on
the screen.
Types of Components in React
In React, we mainly have two types of components: Functional and Class based.

Functional components in React.


Functional components are just like JavaScript functions that accept properties and
return a React element.

We can create a functional component in React by writing a JavaScript function. These


functions may or may not receive data as parameters, we will discuss this later in the
tutorial. The below example shows a valid functional component in React:

Syntax for Functional Components:

Functional Component Example:


Create a function component called welcome.

Class Component in React


The class components are a little more complex than the functional components. A
class component can show inheritance and access data of other components.

Class Component must include the line “extends React.Component” to pass data from
one class component to another class component. We can use JavaScript ES6 classes
to create class-based components in React.
Syntax for Class Components:

The below example shows a valid class-based component in React:

Class Component Example:

Create a class component called welcome.

The components we created in the above two examples are equivalent, and we also
have stated the basic difference between a functional component and a class
component. We will learn about more properties of class-based components in further
tutorials.

Functional Component vs Class Component


A functional component is best suited for cases where the component doesn’t need to
interact with other components or manage complex states. Functional components
are ideal for presenting static UI elements or composing multiple simple components
together under a single parent component.

While class-based components can achieve the same result, they are generally less
efficient compared to functional components. Therefore, it’s recommended to not use
class components for general use.
Rendering React Components
Rendering Components means turning your component code into the UI that users
see on the screen.
React is capable of rendering user-defined components. To render a component in
React we can initialize an element with a user-defined component and pass this
element as the first parameter to ReactDOM.render() or directly pass the component
as the first argument to the ReactDOM.render() method.

The below syntax shows how to initialize a component to an element:

In the above syntax, the ComponentName is the name of the user-defined


component.
Note: The name of a component should always start with a capital letter. This is done
to differentiate a component tag from an HTML tag.

Example
This example renders a component named Welcome to the Screen.

Output: This output will be visible on the http://localhost:3000/ on the browser


window.
Explanation:
Let us see step-wise what is happening in the above example:
 We call the ReactDOM.render() as the first parameter.
 React then calls the component Welcome, which returns <h1>Hello World!
</h1>; as the result.
 Then the ReactDOM efficiently updates the DOM to match with the returned
element and renders that element to the DOM element with id as “root”.

Props
 Props(short for properties) are a way to pass data from the parent
component to the child component.
 Props are like function arguments, you can use them as attributes in
components.

Example:

Components in Components
We can call components inside another component

Example
The above code will give the same output as other examples but here we have called
the Greet component inside the Welcome Component.

For more information on components goto Component Set 2

Conclusion
Components in React allow developers to divide the page UI into many small parts.
These parts work independently and can be used multiple times just like functions.

This tutorial introduces you to the concept of components. We have discussed types of
components and their purpose in web development. This guide will help you
understand web UI and how can you create visually appealing web UI.
4.3. ReactJS | Components – Set 2
In our previous article on ReactJS | Components we had to discuss components, types
of components, and how to render components. In this article, we will see some more
properties of components.

Composing Components: Remember in our previous article, our first example of


GeeksforGeeks’s homepage which we used to explain components? Let’s recall what
we have told, “we can merge all of these individual components to make a parent
component”. This is what we call composing components. We will now create
individual components named Navbar, Sidebar, ArticleList and merge them to create a
parent component named App and then render this App component.

The below code in the index.js file explains how to do this:


Filename- App.js:
You can see in the above output that everything worked well, and we managed to
merge all the components into a single component App.

Decomposing Components: Decomposing a Component means breaking down the


component into smaller components. We have told the thing about composing smaller
components to build a parent component from the very start when we started
discussing components repeatedly. Let us see why there is a need to do so. Suppose
we want to make a component for an HTML form. Let’s say our form will have two
input fields and a submit button. We can create a form component as shown below:

Filename- App.js:
The above code works well to create a form. But let us say now we need some other
form with three input fields. To do this we will have to again write the complete code
with three input fields now. But what if we have broken down the Form component
into two smaller components, one for the input field and another one for the button?
This could have increased our code reusability to a great extent. That is why it is
recommended to React to break down a component into the smallest possible units
and then merge them to create a parent component to increase the code modularity
and reusability. In the below code the component Form is broken down into smaller
components Input and Button.
Till now, we have worked with Components with only static data. That is, we are
writing data directly inside a Component. What if, we want to pass some data to our
Components? React allows us to do so with the help of another property called props.
We will learn about props in detail in our next article.
4.4. ReactJS Pure Components
Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to
customize the default behavior and implement it when the React component should
re-render or update itself.

React JS Pure Components:


Now, ReactJS has provided us with a Pure Component. If we extend a class with Pure
Component, there is no need for shouldComponentUpdate() Lifecycle
Method. ReactJS Pure Component Class compares the current state and props with
new props and states to decide whether the React component should re-render itself
or Not.

In simple words, If the previous value of the state or props and the new value of the
state or props are the same, the component will not re-render itself. Pure
Components restricts the re-rendering when there is no use for re-rendering of the
component. Pure Components are Class Components that
extend React.PureComponent.

Example: This example demonstrates the creation of Pure Components.


Pure Components Key Points:
Shallow Comparison:
 Pure components perform a shallow comparison of the props and states. If
the objects are passed as props or state have the same references, a re-
render is prevented.
Performance Optimization:
 Pure components can provide performance optimizations by preventing
unnecessary re-renders when the data is same and hasn’t modified.
ShouldComponentUpdate:
 Pure components automatically implement
the shouldComponentUpdate() method with a shallow prop and state
comparison. This method returns false if the props and state haven’t
changed.

Extending React Class Components with Pure Components ensures the higher
performance of the Component and ultimately makes your application faster, While in
the case of Regular Component, it will always re-render either value of State and Props
changes or not.

While using Pure Components, Things to be noted are that, In these components, the
Value of State and Props are Shallow Compared (Shallow Comparison) and It also
takes care of “shouldComponentUpdate” Lifecycle method implicitly.

So there is a possibility that if these State and Props Objects contain nested data
structure then Pure Component’s implemented shouldComponentUpdate will return
false and will not update the whole subtree of Children of this Class Component. So
in Pure Component, the nested data structure doesn’t work properly.

In this case, State and Props Objects should be simple objects and Child Elements
should also be Pure, means to return the same output for the same input values at any
instance.
4.5. ReactJS Functional Components
Functional Component is one way to create components in a React Application.
React.js Functional Components helps to create UI components in a Functional and
more concise way. In this article, we will learn about functional components in React,
different ways to call the functional component, and also learn how to create the
functional components. We will also demonstrate the use of hooks in functional
components.

Functional Components in React:


ReactJS Functional components are some of the more common components that will
come across while working in React. These are simply JavaScript functions. We can
create a functional component in React by writing a JavaScript function. These
functions may or may not receive data as parameters. In the functional Components,
the return value is the JSX code to render to the DOM tree.

Ways to call the functional component:


We can call the functions in javaScript in other ways as follows:

1. Call the function by using the name of the function followed by the Parentheses.

2. Call the function by using the functional component method.


4.6. Differences between Functional Components
and Class Components
In this article, we will learn about the differences between functional and class
components in React with the help of an example. We will create a counter and
implement it using both class and functional components to understand the
differences practically.

Functional Components
Functional components are some of the more common components that will come
across while working in React. These are simply JavaScript functions. We can create a
functional component to React by writing a JavaScript function.

Syntax:

Counter using Functional Components


Class Component
This is the bread and butter of most modern web apps built in ReactJS. These
components are simple classes (made up of multiple functions that add functionality
to the application).

Syntax:

Counter using Class Components

In the above example, for functional components, we use hooks (useState) to manage
the state. If you write a function component and realize you need to add some state to
it, previously you had to convert it to a class component. Now you can use a Hook
inside the existing function component to manage the state and no need to convert it
into the Class component. Hooks are a new addition to React 16.8. They let you use
state and other React features without writing a class. Instead of Classes, one can use
Hooks in the Functional component as this is a much easier way of managing the state.
Hooks can only be used in functional components, not in-class components.

Functional Components vs Class Components:

Functional Components Class Component

A functional component is just a plain A class component requires you to extend


JavaScript pure function that accepts props from React. Component and create a
as an argument and returns a React render function that returns a React
element(JSX). element.

There is no render method used in It must have the render() method


functional components. returning JSX (which is syntactically
similar to HTML)

Functional components run from top to The class component is instantiated and
bottom and once the function is returned it different life cycle method is kept alive
can’t be kept alive. and is run and invoked depending on the
phase of the class component.

Also known as Stateless components as Also known as Stateful components


they simply accept data and display them in because they implement logic and state.
some form, they are mainly responsible for
rendering UI.

React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).

Hooks can be easily used in functional It requires different syntax inside a class
components to make them Stateful. component to implement hooks.
Example Example:

Constructors are not used. Constructor is used as it needs to store


state.

You might also like