0% found this document useful (0 votes)
7 views88 pages

UNIT-4

This document provides an introduction to React, a JavaScript library for building user interfaces, and its associated concepts such as the virtual DOM and declarative programming. It contrasts React with traditional frameworks, highlighting its flexibility and efficiency in creating single-page applications. The document also covers the setup of a React environment, the role of ReactDOM, and the structure of React elements and components.

Uploaded by

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

UNIT-4

This document provides an introduction to React, a JavaScript library for building user interfaces, and its associated concepts such as the virtual DOM and declarative programming. It contrasts React with traditional frameworks, highlighting its flexibility and efficiency in creating single-page applications. The document also covers the setup of a React environment, the role of ReactDOM, and the structure of React elements and components.

Uploaded by

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

ADVANCED USER INTERFACE

TECHNOLOGIES
UNIT 4 INTRODUCTION TO REACT AND ITS ROUTER
INTRODUCTION TO CLIENT-SIDE JS FRAMEWORK – BASICS OF ANGULAR 4.0
INTRODUCTION TO CLIENT-SIDE JS FRAMEWORK – BASICS OF ANGULAR 4.0
SYLLABUS

Introduction to React: Platforms and Frameworks tools – Hybrid


frameworks versus Native – React Environment Setup – React
internals – React JSX – React Components and its styling– React
Router: Parameters – Designing single page applications using
React Router
React.js or React in general can be considered an open-source JavaScript library that is

used to create a user interface (UI) for web applications. React Native on the other

hand is used for building cross-platform mobile applications. The underlying

framework is more or less the same as React but instead of using web components, it

uses native mobile components.Jordan Walke, then Facebook software engineer, was

one of the first to build React. Developers may use React to build web apps that can

modify data without refreshing the page.


React is defined as a JavaScript library for building user interfaces
React is a JavaScript “library”. It is not exactly a “framework”. It is not a complete solution and you will
often need to use more libraries with React to form any solution. React does not assume anything about the
other parts in any solution.

Frameworks serve a great purpose, especially for young teams and startups. When working with a
framework, many smart design decisions are already made for you, which gives you a clear path to focus on
writing good application-level logic. However, frameworks come with some disadvantages. For experienced
developers working on large codebases, these disadvantages are sometimes a deal breaker.

Frameworks are not flexible, although some claim to be. A framework usually wants you to code everything
a certain way. If you try to deviate from that way, the framework usually ends up fighting you about it.
Frameworks are also usually large and full of features. If you need to use only a small piece of them, you
have to include the whole thing anyway. Admittedly, this point is changing today but it is still not ideal.
React follows the Unix philosophy because it is a small library that focuses on just one
thing and on doing that thing extremely well. That “one thing” is the second part of the
React’s definition: Building User Interfaces.A User Interface (UI) is anything we put in
front of users to have them interact with a machine. UIs are everywhere, from the simple
buttons on a microwave to the dashboard of a space shuttle.

If the device we are trying to interface can understand JavaScript, we can use React to
describe a UI for it. Since Web browsers understand JavaScript, we can use React to
describe Web UIs.

When you hear the statement that “React is declarative” this is exactly what it means. We
describe UIs with React and tell it what we want (not how to do it). React will take care of
the “how” and translate our declarative descriptions (which we write in the React
language) to actual UIs in the browser. React shares this simple declarative power with
HTML itself, but with React we get to be declarative for HTML UIs that represent
When React was released, there was a lot of buzz about its performance because it
introduced the smart idea of a virtual DOM that can be used to reconcile the actual DOM.

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”,


representation of a UI is kept in memory and synced with the “real” DOM by a library
such as ReactDOM. This process is called reconciliation.

This approach enables the declarative API of React: You tell React what state you want the
UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute
manipulation, event handling, and manual DOM updating that you would otherwise have
to use to build your app.
React is a JavaScript library (not a framework) that creates user interfaces (UIs) in a
predictable and efficient way using declarative code. You can use it to help build single
page applications and mobile apps, or to build complex apps if you utilise it with other
libraries.

React works in declarative code. To show what we mean by declarative code, we want you
to imagine the following code expressed as an app.
What you picture could look like the screen below, with a navbar, a header, a filter, and a
list. That’s because each line of code declares what each element of the app is.

So, you’ve read the code and learned something fundamental about the design. That’s
because declarative code describes what we want instead of saying how to do it, as you
would with imperative code.

At its core, declarative code is like visiting a restaurant and ordering a meal. You tell the
waiter what you want, but you don’t go in the kitchen to tell the chef how to cook it.
Declarative code describes the end result, but doesn’t act as a step-by-step guide of how to
do it.

In practice, that means declarative code is lightweight, easier to understand and change,
and has less bugs.
Imperative Versus Declarative
Functional programming is a part of a larger programming paradigm: declarative
programming. Declarative programming is a style of programming where applications are
structured in a way that prioritizes describing what should happen over defining how it
should happen.
In order to understand declarative programming, we’ll contrast it with imperative
programming, or a style of programming that is only concerned with how to achieve
results with code. Let’s consider a common task: making a string URL-friendly. Typically,
this can be accomplished by replacing all of the spaces in a string with hyphens, since
spaces are not URL-friendly. First, let’s examine an imperative approach to this task:
var string = "This is the midday show with Cheryl Waters";
var urlFriendly = "";
for (var i=0; i<string.length; i++) {
if (string[i] === " ") {
urlFriendly += "-";
} else {
urlFriendly += string[i];
}
}
console.log(urlFriendly);
In this example, we loop through every character in the string, replacing spaces as they
occur.

The structure of this program is only concerned with how such a task can be achieved.

We use a for loop and an if statement, and set values with an equality operator. Just
looking at the code alone does not tell us much.

Imperative programs require lots of comments in order to understand what is going on.
Now let’s look at a declarative approach to the same problem:

const string = "This is the mid day show with Cheryl Waters"

const urlFriendly = string.replace(/ /g, "-")

console.log(urlFriendly)

Here we are using string.replace along with a regular expression to replace all instances of
spaces with hyphens. Using string.replace is a way of describing what is supposed to
happen: spaces in the string should be replaced. The details of how spaces are dealt with
are abstracted away inside the replace function. In a declarative program, the syntax itself
describes what should happen and the details of how things happen are abstracted away.
Now, let’s consider the task of building a document object model, or DOM. An imperative
approach would be concerned with how the DOM is constructed:
var target = document.getElementById('target');
var wrapper = document.createElement('div');
var headline = document.createElement('h1');
wrapper.id = "welcome";
headline.innerText = "Hello World";
wrapper.appendChild(headline);
target.appendChild(wrapper);
This code is concerned with creating elements, setting elements, and adding them to the
document. It would be very hard to make changes, add features, or scale 10,000 lines of
code where the DOM is constructed imperatively.
Now let’s take a look at how we can construct a DOM declaratively using a React component:
const { render } = ReactDOM
const Welcome = () => (
<div id="welcome">
<h1>Hello World</h1>
</div>
)
render(
<Welcome />,
document.getElementById('target')
)
React is declarative. Here, the Welcome component describes the DOM that should be rendered.
The render function uses the instructions declared in the component to build the DOM, abstracting
away the details of how the DOM is to be rendered. We can clearly see that we want to render our
Welcome component into the element with the ID of 'target'.
Pure React
Page Setup
In order to work with React in the browser, we need to include two libraries: React and
ReactDOM. React is the library for creating views. ReactDOM is the library used to
actually render the UI in the browser.
We also need an HTML element that ReactDOM will use to render the UI. You can see
how the scripts and HTML elements are added in Example 4-1. Both libraries are available
as scripts from the Facebook CDN.
HTML document setup with React
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pure React Samples</title>
</head>
<body>
<!-- Target container -->
<div class="react-container"></div>
<!-- React library & ReactDOM-->
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script>
// Pure React and JavaScript code
</script>
</body>
</html>
The Virtual DOM
HTML is simply a set of instructions that a browser follows when constructing the
document object model, or DOM. The elements that make up an HTML document become
DOM elements when the browser loads HTML and renders the user interface.
Let’s say that you have to construct an HTML hierarchy for a recipe. A possible solution
for such a task might look something like this:
<section id="baked-salmon">
<h1>Baked Salmon</h1>
<ul class="ingredients">
<li>1 lb Salmon</li>
<li>1 cup Pine Nuts</li>
<li>2 cups Butter Lettuce</li>
<li>1 Yellow Squash</li>
<li>1/2 cup Olive Oil</li>
<li>3 cloves of Garlic</li>
</ul>
<section class="instructions">
<h2>Cooking Instructions</h2>
<p>Preheat the oven to 350 degrees.</p>
<p>Spread the olive oil around a glass baking dish.</p>
<p>Add the salmon, garlic, and pine nuts to the dish.</p>
<p>Bake for 15 minutes.</p>
<p>Add the yellow squash and put back in the oven for 30 mins.</p>
<p>Remove from oven and let cool for 15 minutes.
Add the lettuce and serve.</p>
</section>
</section>
In HTML, elements relate to each other in a hierarchy that resembles a family tree. We
could say that the root element has three children: a heading, an unordered list of
ingredients, and a section for the instructions.

Traditionally, websites have consisted of independent HTML pages. When the user
navigated these pages, the browser would request and load different HTML documents.

The invention of AJAX brought us the single-page application, or SPA. Since browsers
could request and load tiny bits of data using AJAX, entire web applications could now run
out of a single page and rely on JavaScript to update the user interface.
In an SPA, the browser initially loads one HTML document. As users navigate through the
site, they actually stay on the same page.
JavaScript destroys and creates a new user interface as the user interacts with the
application. It may feel as though you are jumping from page to page, but you are actually
still on the same HTML page and JavaScript is doing the heavy lifting.
The DOM API is a collection of objects that JavaScript can use to interact with the
browser to modify the DOM. If you have used document.createElement or
document.appendChild, you have worked with the DOM API. Updating or changing
rendered DOM elements in JavaScript is relatively easy.
However, the process of inserting new elements is painfully slow.This means if web
developers are meticulous about how they make changes to UI, they can improve the
performance of their applications.
Managing DOM changes with JavaScript efficiently can become very complicated and
time-consuming. From a coding perspective, it is easier to clear all the children of a
particular element and reconstruct them than it would be to leave those child elements in
place and attempt to efficiently update them.
The problem is that we may not have the time or the advanced knowledge of JavaScript to
work efficiently with the DOM API every time we build a new application. The solution is
React. React is a library that is designed to update the browser DOM for us.
We no longer have to be concerned with the complexities associated with building
performant SPAs because React can do that for us. With React, we do not interact with the
DOM API directly. Instead, we interact with a virtual DOM, or set of instructions that
React will use to construct the UI and interact with the browser.
The virtual DOM is made up of React elements, which conceptually seem similar to
HTML elements, but are actually JavaScript objects. It is much faster to work directly
with JavaScript objects than it is to work with the DOM API.

We make changes to a JavaScript object, the virtual DOM, and React renders those
changes for us using the DOM API as efficiently as possible.
React Elements
The browser DOM is made up of DOM elements. Similarly, the React DOM is made up of
React elements. DOM elements and React elements may look the same, but they are
actually quite different.
A React element is a description of what the actual DOM element should look like. In
other words, React elements are the instructions for how the browser DOM should be
created.
We can create a React element to represent an h1 using React.createElement:
React.createElement("h1", null, "Baked Salmon")
The first argument defines the type of element that we wish to create. In this case, we want
to create a heading-one element.

The third argument represents the element’s children, any nodes that are inserted between
the opening and closing tag. The second argument represents the element’s properties. This
h1 currently does not have any properties.

During rendering, React will convert this element to an actual DOM element:

<h1>Baked Salmon</h1>
When an element has attributes, they can be described with properties. Here is a sample of
an HTML h1 tag that has id and data-type attributes:

React.createElement("h1",{id: "recipe-0", 'data-type': "title"},"Baked Salmon")

<h1 data-reactroot id="recipe-0" data-type="title">Baked Salmon</h1>

The properties are similarly applied to the new DOM element: the properties are added to
the tag as attributes, and the child text is added as text within the element.
data-reactroot

data-reactroot will always appear as an attribute of the root element of your React
component.

Prior to version 15, React IDs were added to each node that was a part of your component.

This helped with rendering and keeping track of which elements needed to be updated.

Now, there is only an attribute added to the root, and rendering is kept track of based on
the hierarchy of elements.
ReactDOM
ReactDOM contains the tools necessary to render React elements in the browser.
ReactDOM is where we will find the render method as well as the renderToString and
renderToStaticMarkup methods that are used on the server. All the tools necessary to
generate HTML from the virtual DOM are found in this library.
We can render a React element, including its children, to the DOM with
ReactDOM.render. The element that we wish to render is passed as the first argument and
the second argument is the target node, where we should render the element:
var dish = React.createElement("h1", null, "Baked Salmon")
ReactDOM.render(dish, document.getElementById('react-container'))
Rendering the title element to the DOM would add a heading-one element to the div with
the id of react-container, which we would already have defined in our HTML.
Example 4-3. React added the h1 element to the target: react-container
<body>
<div id="react-container">
<h1>Baked Salmon</h1>
</div>
</body>
All of the DOM rendering functionality in React has been moved to ReactDOM because
we can use React to build native applications as well. The browser is just one target for
React.
Children
ReactDOM allows you to render a single element to the DOM. React tags this as
data-reactroot. All other React elements are composed into a single element using nesting.

React renders child elements using props.children. In the previous section, we rendered a
text element as a child of the h1 element, and this props.children was set to "Baked
Salmon". We could render other React elements as children too, creating a tree of
elements. This is why we use the term component tree. The tree has one root component
from which many branches grow.
Let’s consider the unordered list that contains ingredients in Example 4-4.
Example 4-4. Ingredients list
<ul>
<li>1 lb Salmon</li>
<li>1 cup Pine Nuts</li>
<li>2 cups Butter Lettuce</li>
<li>1 Yellow Squash</li>
<li>1/2 cup Olive Oil</li>
<li>3 cloves of Garlic</li>
</ul>
In this sample, the unordered list is the root element, and it has six children. We can
represent this ul and its children with React.createElement (Example 4-5).
Example 4-5. Unordered list as React elements
React.createElement( "ul", null,
React.createElement("li", null, "1 lb Salmon"),
React.createElement("li", null, "1 cup Pine Nuts"),
React.createElement("li", null, "2 cups Butter Lettuce"),
React.createElement("li", null, "1 Yellow Squash"),
React.createElement("li", null, "1/2 cup Olive Oil"),
React.createElement("li", null, "3 cloves of Garlic")
)
Every additional argument sent to the createElement function is another child element.
React creates an array of these child elements and sets the value of props.children to that
array. If we were to inspect the resulting React element, we would see each list item
represented by a React element and added to an array called props.children.

Example 4-6. Resulting React element

{"type": "ul",
"props": {
"children": [
{ "type": "li", "props": { "children": "1 lb Salmon" } ... },
{ "type": "li", "props": { "children": "1 cup Pine Nuts"} ... },
{ "type": "li", "props": { "children": "2 cups Butter Lettuce" } ... },
{ "type": "li", "props": { "children": "1 Yellow Squash"} ... },
{ "type": "li", "props": { "children": "1/2 cup Olive Oil"} ... },
{ "type": "li", "props": { "children": "3 cloves of Garlic"} ... }]...}}
We can now see that each list item is a child. Earlier in this chapter, we introduced HTML
for an entire recipe rooted in a section element. To create this using React, we’ll use a series
of createElement calls,
Example 4-7. React Element tree
React.createElement("section", {id: "baked-salmon"},
React.createElement("h1", null, "Baked Salmon"),
React.createElement("ul", {"className": "ingredients"},
React.createElement("li", null, "1 lb Salmon"),
React.createElement("li", null, "1 cup Pine Nuts"),
React.createElement("li", null, "2 cups Butter Lettuce"),
React.createElement("li", null, "1 Yellow Squash"),
React.createElement("li", null, "1/2 cup Olive Oil"),
React.createElement("li", null, "3 cloves of Garlic")
),
React.createElement("section", {"className": "instructions"},
React.createElement("h2", null, "Cooking Instructions"),
React.createElement("p", null, "Preheat the oven to 350 degrees."),
React.createElement("p", null,
"Spread the olive oil around a glass baking dish."),
React.createElement("p", null, "Add the salmon, garlic, and pine..."),
React.createElement("p", null, "Bake for 15 minutes."),
React.createElement("p", null, "Add the yellow squash and put..."),
React.createElement("p", null, "Remove from oven and let cool for 15 ....") ) )
Why React?
React’s popularity today has eclipsed that of all other front-end development
frameworks. Here is why:
● Easy creation of dynamic applications: React makes it easier to create dynamic
web applications because it requires less coding and offers more functionality, as
opposed to JavaScript, where coding often gets complex very quickly.
● Improved performance: React uses Virtual DOM, thereby creating web
applications faster. Virtual DOM compares the components’ previous states and
updates only the items in the Real DOM that were changed, instead of updating all
of the components again, as conventional web applications do.
● Reusable components: Components are the building blocks of any React
application, and a single app usually consists of multiple components. These
components have their logic and controls, and they can be reused throughout the
application, which in turn dramatically reduces the application’s development time.
Unidirectional data flow: React follows a unidirectional data flow. This means that
when designing a React app, developers often nest child components within parent
components. Since the data flows in a single direction, it becomes easier to debug
errors and know where a problem occurs in an application at the moment in
question.

● Small learning curve: React is easy to learn, as it mostly combines basic HTML
and JavaScript concepts with some beneficial additions. Still, as is the case with
other tools and frameworks, you have to spend some time to get a proper
understanding of React’s library.
● It can be used for the development of both web and mobile apps: We already
know that React is used for the development of web applications, but that’s not
all it can do. There is a framework called React Native, derived from React
itself, that is hugely popular and is used for creating beautiful mobile
applications. So, in reality, React can be used for making both web and mobile
applications.

● Dedicated tools for easy debugging: Facebook has released a Chrome extension
that can be used to debug React applications. This makes the process of
debugging React web applications faster and easier.
Features of React
JSX - JavaScript Syntax Extension
JSX is a syntax extension to JavaScript. It is used with React to describe what the user
interface should look like. By using JSX, we can write HTML structures in the same file
that contains JavaScript code. This makes the code easier to understand and debug, as it
avoids the usage of complex JavaScript DOM structures.
Virtual DOM
React keeps a lightweight representation of the “real” DOM in the memory, and that is
known as the “virtual” DOM (VDOM). Manipulating real DOM is much slower than
manipulating VDOM because nothing gets drawn on the screen. When the state of an
object changes, VDOM changes only that object in the real DOM instead of updating all of
the objects. It may all seem a bit overwhelming for now, so let’s first understand what
DOM is, and then we’ll go through how VDOM and real DOM interact with each other.
One-way Data Binding

React’s one-way data binding keeps everything modular and fast. A unidirectional
data flow means that when a developer designs a React app, they often nest child
components within parent components. This way, a developer knows where and
when an error occurs, giving them better control of the whole web application.

Debugging

React applications are easy to test due to a large developer community. Facebook
even provides a small browser extension that makes React debugging faster and
easier.
Platform:

React has been one of the most popular libraries for building web applications since
its initial release in 2013. Developers around the world love it so much that they
have invented unique ways to make React available not only for web development but
also for mobile and desktop.
1. Reusing React Components Across Apps: Bit.dev

A single product may have a web app, a static marketing site, an iOS app, and an
Android app. That’s a lot! To keep things simple and affordable, we have to reuse
code between these projects. That’s where Bit.dev, a cloud component hub, helps us
the most. Bit.dev makes it easy to publish React components from any codebase so
that each React project quickly becomes another source for reusable components to
use in all other projects. Bit helps us reuse components, not only by making
publishing easier, but also by offering an intuitive platform to document, organize,
and render our reusable components. That’s important since components that aren’t
easily found will not be reused that often.
2. Static Websites: Gatsby
A static site is a website that provides a fixed content, usually rendered from markup
languages like markdown into HTML. Static site gained popularity because it
requires no request to the back-end to retrieve content from the database. The
content is already built, and you only need to serve it to users. A static site is also
easier to build because they require no back-end to begin with.

In a static site, the HTML is served from a CDN instead of a server. It’s perfect for
several types of websites that doesn’t require lots of back-end processing power like
blogs, portfolio sites, galleries, documentation sites. Gatsby is a React-based static
site generator that’s very popular because of its exceptional user experience (blazing
fast load) and developer experience (simple APIs, easily extendable with plugins).
Some web apps created with Gatsby include the documentation of React itself.
3. React for mobile (Android and iOS): React Native
JavaScript has entered the mobile app development scene as early as 2009 since the
invention of PhoneGap. In the beginning, the app that can be created with JavaScript is
just a website that’s styled to look like an app and served through a WebView. Note: A
WebView is a core View class of Android and iOS that’s used to display web pages.
Fast forward today, we have React Native, a mobile application framework that transforms
JavaScript code into native code, allowing your application to run just like a native
application instead of using a WebView. Using React Native, you can build
high-performance mobile apps without learning a native mobile programming language like
Kotlin or Swift. Some popular mobile apps built using React Native include Walmart,
Instagram, and of course Facebook itself.
4. React for desktop: Electron

Electron is an open-source framework for building cross-platform desktop


applications targeting Windows, macOS, and Linux. Under the hood, Electron used
Chromium, the open-source project behind Chrome OS and Chrome web browser
which is built by Google. Electron itself is framework agnostic. It can be used
together with JavaScript frameworks like Angular, Vue, or React.
To skip configuring the project and start coding right away, you can use
electron-react-boilerplate. It’s a starter code that has done the legwork of
integrating Electron with React, Redux, React Router, Webpack, and React Hot
Loader for rapid application development (HMR).
5. React SSR framework: NextJS
Server-Side Rendering is not a certain kind of app category, but more of a technique to
optimize the initial load of your application content. Apps built using React are rendered on
the user’s browser, which means a bundle of JS files must be downloaded before processing.
This increases the initial load time before your users can interact with your app. Server-Side
Rendering is a method for optimizing React app’s performance and SEO. The first request is
rendered from the server, while the subsequent requests will load from the client. Because the
first request is already rendered from the server, search engines will be able to pick up on
important meta data for better SEO results. You definitely can implement SSR without any
framework, but it’s not recommended because you have to handle the configuration like
minification and bundling on your own. NextJS is actually a complete React framework with
several benefits, and SSR is one of them. By using NextJS, you can create a pre-rendered
React app with as few lines of code as possible.
Hybrid frameworks versus Native
Hybrid apps are essentially websites embedded in a mobile app through what we call
a webview. They are developed using HTML5, CSS, and Javascript and execute the
same code regardless of the platform in which they run. They can, with tools like
PhoneGap and Cordova, use the native features of a device, like GPS or camera.

Native apps are developed in the language required by the platform it targets
Objective-C or swift for iOS, Java for Android etc. The code written is not shared
across platforms and their behavior varies. They have direct access to all features
offered by the platform without any restriction.
The discussion around React Native vs Hybrid apps for startups has been doing the rounds
ever since 2015 – the first time we heard of React Native. The debate is not of which
platform is more efficient but of which is more suited for startups’ business needs: Faster
time to market, efficient quality, and low cost of development.

Here are the many benefits of choosing hybrid apps that businesses swear upon –

They get to reach a wider audience on multiple platforms

They get to develop an offline version of the app

The apps do not need advanced graphics performance such as ones needed by native
applications.
When you take into consideration the compromises that your startup will have to face in the sense of

features and performances that your users expect, the overall dire impact of choosing hybrid apps

becomes prominent and the many limitations of hybrid apps surface. You will have to ask yourself a

few prominent questions before you make an investment in hybrid app development:

Does your user really wish to use an application that is unresponsive and slow?

If you are on iOS, would you want to use an application that looks like an Android app?

If you are on Android, would you want to spend time in an application that looks and operates

like an iOS application?

The answer is an obvious no, right?


Low performance

A comparison between Native and Hybrid apps shows just how far behind Hybrid lacks in terms of

performance when compared to Native. Hybrid apps introduce an additional layer between source

code and the targeted mobile platform: An expected result of this is a loss of performance. While it

varies from one application to another – how evident the difference would be – the fact that

Facebook migrated their app from HTML5 to React Native says a lot. This is just one example of

the scope of a difference it can bring to large-scale applications.


2. Difficult debugging

The extra layer that Hybrid app creation introduces makes the debugging process a complete

nightmare. The mobile app developers have to rely on the framework to play around with

targeted operating systems in the hope that no new bugs are introduced in their application.

On the other side, since it is less likely that the developers would carry a complete

understanding of the chosen platform, finding out the exact reason behind the issue can be

pretty lengthy.
3. User management

When you request the clients to create an account and sign in whenever they load your

application, you’ll struggle to gather utilization and performance metrics which could

improve your application. Then again, on other hand, adding a sign in screen each time the

user loads your application could restrict engagement and increase the bounce rates.
4. Lacks 3D support and graphics

If you need any 3D component or eye-catching graphic design on your application. At that

point the native application is the better decision on the grounds that the hybrid

applications won’t have eye-catching illustrations and 3D support. If you want to have 3D

support on hybrid applications, then developers need to put forth an extra effort to fulfill

the design quality gap with the assistance of third party tools like Unity 3D.
5. Challenge in adding the latest features

One of the sure-shot ways of startup success is to stand at the very center of progress and

make use of all upcoming software capabilities and features set. But sadly, one of the

biggest disadvantages of Hybrid apps is that it is extremely difficult to add new features

and capabilities in the Hybrid framework.


So where does this leave the entrepreneurs who are tight on a budget and are not ready to

make a Native app investment?

Well, this is where React Native mobile app comes in and provides a clear native and

hybrid app difference for startup debate. Here are the ways React Native has killed Hybrid

apps for good – at least for startups who have now refused to ignore quality over cost and

time benefits. Ones who chose to take React Native’s side in the comparison between

React Native & Hybrid apps.


1. React native cross-platform apps look and function like native applications

The Native framework uses the same react native components platform which the native iOS or

Android app languages make us of. Hybrid apps, on the other hand, are simply a web view that is

wrapped in a native container that runs and behaves like a web app. When we talk about the

difference between native app and hybrid app for startups, the traditional hybrid app frameworks

don’t stand anywhere near the smooth UX and speed offering that React Native apps come with.

Even the most well-designed and slick web application would never be as smooth as after react native

UI development.
2. React native enables sharing of a single-codebase between iOS and Android

One of the main reasons why startups choose React Native is because of its write once run on

multiple platforms nature. One of the primal features of the React Native framework makes it

possible to give startups a high performing application with half the time and cost restrictions that

Native apps come with. At Appinventiv, we have built a number of React Native apps, and we are

always in awe of how more than 80% of the code can be shared between iOS and Android versions

of the app, making the process extremely time and cost-efficient.


3. React Native uses ReactJS’s programming model

One of the biggest benefits of React native app development is that at its core, it is a

JavaScript framework that shares the programming model with the famous ReactJS

web language. The conceptual framework that is used to develop ReactJS web apps

comes in use when creating React Native apps. The startup benefit in this situation is

the fact that they only have to invest in one developer instead of three: Android, iOS,

and web developers.


4. React native framework for external integration and shared knowledge.

Ever since its official release in 2015, React Native has gained rapid awareness and interest in the

developers’ community. React native framework comes with a rich open-source ecosystem for

external integration and shared knowledge. It took no time to become the market leader in the

new-gen of cross-platform app development. One of the main frictions that the majority of react

native app development company faced was in terms of integrating third-party systems or creating

custom UI control that was not supported in React Native natively. But luckily, the quick adoption of

the React Native framework has resulted in more third-party integrations in the recent time.
5. React native backs some of the top apps of the marketplace

There can hardly be a stronger point in the React Native vs Hybrid apps for startups debate

than the fact that React Native backs some of the biggest apps of the world: Instagram,

Facebook, Tesla, Bloomberg, Walmart, etc. The extent of React Native adoption across a

wide industry spectrum is a direct signal of its permanence.


6. Comes with components that enable hybrid apps to render natively

Gone is the time of WebView component dominance. The reality of today is React
Native’s building squares which are reusable local segments that get together in locales.
The elements and components that you would normally use in Android and iOS are
already there in React Native to give you that consistent look and functioning. This section
based structure empowers a React Native development company (in different areas like
Texas, California, etc.) to fabricate the apps with a quicker, web-style way for dealing with
progression. For example, companies with app development using react native in Texas
provide a high degree of code reuse with prevailing UI which follows each platform’s style
guide and best practices. The end result of it all is a swift application that comes backed
with the expediency of the local portable system.
7. React native is synonymous with an intuitive user interface (UI)

Compared to other JavaScript frameworks like React or Angular, React Native is more

exclusive to mobile. The resulting UI of the React Native application development is one that

is extremely responsive and fluid – all thanks to the asynchronous JavaScript connections

that are present in the native environment. For a startup app development company, it means

that the application has a rapid load time and smooth feel compared to hybrid applications.
8. Enables third-party plugin connectivity with no-glitch experience

One of the major reasons for choosing React Native for startup app development is the

presence of several third-party integrations. They enable startups to not rely on WebView

for performing functions. For instance, if you wish to add Google Maps in the application,

React Native will let you connect the plugin using the native module.
9. The framework is immensely budget-friendly

When running a startup, cost crunch remains the primal cause of concern behind every

startup app development solutions. The fact that react native app development services

revolve around a single codebase and multi-platform capability, the time it takes to build a

react native application is much less. The less development time in the software world is

equal to the low development cost.


10. Reusable native component

The WebView part that is utilized to create hybrid mobile applications


is currently of no use.

React native app developers are currently creating blocks with the
reusable ‘native components’ that can be aggregated directly to the
native applications.

Besides, React Native has counterparts of the components and


elements utilized in iOS and Android application development.

Thus, this enables the designers to create a reliable look, speed, feel,
and fundamental functionalities of the native mobile application.
React JSX:

React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
But instead of using regular JavaScript, React code should be written in something called
JSX.

Let us see a sample JSX code:

const ele = <h1>This is sample JSX</h1>;

The above code snippet somewhat looks like HTML and it also uses a JavaScript-like
variable but is neither HTML nor JavaScript, it is JSX. JSX is basically a syntax extension
of regular JavaScript and is used to create React elements. These elements are then
rendered to the React DOM.
React Components
Every user interface is made up of parts. The recipe example we’ll use here has a
few recipes, each made up of parts.
In React, we describe each of these parts as a component. Components allow us to
reuse the same DOM structure for different recipes or different sets of data.
When considering a user interface that you want to build with React, look for
opportunities to break down your elements into reusable pieces.
For example, the recipes in Figure 4-4 each have a title, ingredients list, and
instructions. All are part of a larger recipe or app component.
We could create a component for each of the highlighted parts: ingredients,
instructions, and so on. Think about how scalable this is. If we want to display one
recipe, our component structure will support this. If we want to display 10,000
recipes, we’ll just create new instances of that component.
React.createClass
When React was first introduced in 2013, there was only one way to create a component: the createClass
function. New methods of creating components have emerged, but createClass is still used widely in React
projects. The React team has indicated, however, that createClass may be deprecated in the future. we can
create a React component using React.createClass thatreturns a single unordered list element that contains a
child list item for each ingredient in an array.
Example 4-12. Ingredients list as a React component
const IngredientsList = React.createClass({
displayName: "IngredientsList",
render() {
return React.createElement("ul", {"className": "ingredients"},
React.createElement("li", null, "1 lb Salmon"),
React.createElement("li", null, "1 cup Pine Nuts"),
React.createElement("li", null, "2 cups Butter Lettuce"),
React.createElement("li", null, "1 Yellow Squash"),
React.createElement("li", null, "1/2 cup Olive Oil"),
React.createElement("li", null, "3 cloves of Garlic")
)
}
})
const list = React.createElement(IngredientsList, null, null)
ReactDOM.render(
list,
document.getElementById('react-container')
)
Components allow us to use data to build a reusable UI. In the render function, we can use the this keyword to refer to the
component instance, and properties can be accessed on that instance with this.props. Here, we have created an element using
our component and named it Ingredients List:

<IngredientsList>

<ul className="ingredients">

<li>1 lb Salmon</li>

<li>1 cup Pine Nuts</li>

<li>2 cups Butter Lettuce</li>

<li>1 Yellow Squash</li>

<li>1/2 cup Olive Oil</li>

<li>3 cloves of Garlic</li>

</ul>

</IngredientsList>
Data can be passed to React components as properties. We can create a reusable list of ingredients by passing that data
to the list as an array:

const IngredientsList = React.createClass({


displayName: "IngredientsList",
render() {
return React.createElement("ul", {className: "ingredients"},
this.props.items.map((ingredient, i) =>
React.createElement("li", { key: i }, ingredient)))}})
const items = [
"1 lb Salmon",
"1 cup Pine Nuts",
"2 cups Butter Lettuce",
"1 Yellow Squash",
"1/2 cup Olive Oil",
"3 cloves of Garlic"
]
ReactDOM.render(
React.createElement(IngredientsList, {items}, null),
document.getElementById('react-container'))
Now, let’s look at ReactDOM. The data property items is an array with six ingredients. Because we made the li tags
using a loop, we were able to add a unique key using the index of the loop:

<IngredientsList items=[...]>

<ul className="ingredients">

<li key="0">1 lb Salmon</li>

<li key="1">1 cup Pine Nuts</li>

<li key="2">2 cups Butter Lettuce</li>

<li key="3">1 Yellow Squash</li>

<li key="4">1/2 cup Olive Oil</li>

<li key="5">3 cloves of Garlic</li>

</ul>

</IngredientsList>
React.Component
one of the key features included in the ES6 spec is React.Component, an abstract class that we can use to
build new React components. We can create custom components through inheritance by extending this class
with ES6 syntax. We can create Ingredients List using the same syntax.

class IngredientsList extends React.Component {

renderListItem(ingredient, i) {

return React.createElement("li", { key: i }, ingredient)}

render() {

return React.createElement("ul", {className: "ingredients"},

this.props.items.map(this.renderListItem))}}
Stateless Functional Components
Stateless functional components are functions, not objects; therefore, they do not
have a “this” scope. Because they are simple, pure functions, we’ll use them as much
as possible in our applications. There may come a point where the stateless
functional component isn’t robust enough and we must fall back to using class or
createClass, but in general the more you can use these, the better.
Stateless functional components are functions that take in properties and return a
DOM element. Stateless functional components are a good way to practice the rules
of functional programming. You should strive to make each stateless functional
component a pure function. They should take in props and return a DOM element
without causing side effects. This encourages simplicity and makes the codebase
extremely testable.
Creating a stateless functional component

const IngredientsList = props =>React.createElement("ul", {className:


"ingredients"},

props.items.map((ingredient, i) =>React.createElement("li", { key: i }, ingredient)

))

We would render this component with ReactDOM.render, the exact same way we
render components created with createClass or ES6 class syntax. This is just a
function. The function collects data through the props arguments and returns an
unordered list for each item that is sent to the props data.
DOM Rendering
Since we are able to pass data to our components as props, we can separate our
application’s data from the logic that is used to create the UI. This gives us an
isolated set of data that is much easier to work with and manipulate than the
document object model. When we change any of the values in this isolated dataset,
we change the state of our application.
Imagine storing all of the data in your application in a single JavaScript object.
Every time you made a change to this object, you could send it to a component as
props and rerender the UI. This means that ReactDOM.render is going to be doing a
lot of heavy lifting.
In order for React to work in a reasonable amount of time, ReactDOM.render has to work smart, and
it does. Instead of emptying and reconstructing the entire DOM, ReactDOM.render leaves the current
DOM in place and only applies the minimal amount of changes required to mutate the DOM.

Let’s say we had an app that displayed the mood of our five team members using either a smiley face
or a frowny face. We can represent the mood of all five individuals in a single JavaScript array:

["smile", "smile", "frown", "smile", "frown"];

If something breaks and the team has to work all weekend, we can reflect the team’s new mood
simply by changing the data in this array, producing the result shown in the image that follows:

["frown", "frown", "frown", "frown", "frown"];


How many changes do we have to make to the first array to make it look like the
second array of all frowns?

["smile", "smile", "frown", "smile", "frown"];

["frown", "frown", "frown", "frown", "frown"];

We would need to change the first, second, and fourth values from a smile to a
frown. Therefore, we can say that it would take three mutations to change the first
array of data to match the second.
Example 4-17. Start with the current list

<ul>

<li class="smile">smile</li>

<li class="smile">smile</li>

<li class="frown">frown</li>

<li class="smile">smile</li>

<li class="frown">frown</li>

</ul>
This involves the following steps:

1. Empty the current data:

<ul> </ul>

2. Begin looping through data and build the first list item:

<ul> <li class="frown">frown</li> </ul>

3. Build and add the second list item:

<ul> <li class="frown">frown</li> <li class="frown">frown</li>

</ul>
Build and append the fifth list item:

<ul>

<li class="frown">frown</li>

<li class="frown">frown</li>

<li class="frown">frown</li>

<li class="frown">frown</li>

<li class="frown">frown</li>

</ul>

If we change the UI by erasing and rebuilding the DOM, we are creating and inserting five new DOM elements. Inserting an
element into the DOM is one of the most costly DOM API operations—it’s slow. In contrast, updating DOM elements that are
already in place performs much more quickly than inserting new ones.
ReactDOM.render makes changes by leaving the current DOM in place and simply
updating the DOM elements that need to be updated. In our example, there are only
three mutations, so ReactDOM.render only needs to update three DOM elements
If new DOM elements need to be inserted, ReactDOM will insert them, but it tries to
keep DOM insertions (the most costly operation) to a minimum.

This smart DOM rendering is necessary for React to work in a reasonable amount of
time because our application state changes a lot. Every time we change that state,
we are going to rely on ReactDOM.render to efficiently rerender the UI.
Factories
So far, the only way we have created elements has been with React.createElement.
Another way to create a React element is to use factories. A factory is a special
object that can be used to abstract away the details of instantiating objects. In
React, we use factories to help us create React element instances. React has built-in
factories for all commonly supported HTML and SVG DOM elements, and you can
use the React.createFactory function to build your own factories around specific
components.
For example, consider our h1 element from earlier in this chapter:
<h1>Baked Salmon</h1>
Instead of using createElement, we can create a React element with a built-in
factory
Using createFactory to create an h1
React.DOM.h1(null, "Baked Salmon")
In this case, the first argument is for the properties and the second argument is for the
children. We can also use DOM factories to build an unordered list, as in
Building an unordered list with DOM factories

React.DOM.ul({"className": "ingredients"},
React.DOM.li(null, "1 lb Salmon"),
React.DOM.li(null, "1 cup Pine Nuts"),
React.DOM.li(null, "2 cups Butter Lettuce"),
React.DOM.li(null, "1 Yellow Squash"),
React.DOM.li(null, "1/2 cup Olive Oil"),
React.DOM.li(null, "3 cloves of Garlic")
)

You might also like