0% found this document useful (0 votes)
8 views19 pages

Unit 1

ReactJS is a component-based JavaScript library developed by Facebook for building dynamic user interfaces, focusing on performance and maintainability. It utilizes a virtual DOM for efficient updates and supports a declarative approach to UI design, along with features like JSX, one-way data binding, and state management. The document also covers the setup of a React development environment and compares React with other frameworks like Angular and Vue.js.

Uploaded by

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

Unit 1

ReactJS is a component-based JavaScript library developed by Facebook for building dynamic user interfaces, focusing on performance and maintainability. It utilizes a virtual DOM for efficient updates and supports a declarative approach to UI design, along with features like JSX, one-way data binding, and state management. The document also covers the setup of a React development environment and compares React with other frameworks like Angular and Vue.js.

Uploaded by

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

❖ Unit -1 INTRODUCTION OF REACT JS

ReactJS is a component-based JavaScript library used to build dynamic and


interactive user interfaces. It simplifies the creation of single-page applications
(SPAs) with a focus on performance and maintainability.

• It is developed and maintained by Facebook.


• The latest version of React is React 19.
• Uses a virtual DOM for faster updates.
• Supports a declarative approach to designing UI components.
• Ensures better application control with one-way data binding.
• 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.
Here’s how the process works:
1. Actual DOM and Virtual DOM

• Initially, there is an Actual DOM(Real DOM) containing a div with two child
elements: hi and h2.
• React maintains a previous Virtual DOM to track the UI state before any
updates.
2. Detecting Changes

• When a change occurs (e.g., adding a new h3 element), React generates a


New Virtual DOM.
• React compares the previous Virtual DOM with the New Virtual DOM using a
process called reconciliation.
3. Efficient DOM Update
• React identifies the differences (in this case, the new h3 element).

• Instead of updating the entire DOM, React updates only the changed part in the
New Actual DOM, making the update process more efficient.
Key Features of React

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

React uses a Virtual DOM to optimize UI rendering. Instead of updating the entire
real DOM directly, React:
• Creates a lightweight copy of the DOM (Virtual DOM).
• Compares it with the previous version to detect changes (diffing).

• Updates only the changed parts in the actual DOM (reconciliation), improving
performance.
2. Component-Based Architecture

React follows a component-based approach, where the UI is broken down into


reusable components. These components:

• Can be functional or class-based.


• It allows code reusability, maintainability, and scalability.

3. JSX (JavaScript XML)


React usesJSX, a syntax extension that allows developers to write HTML inside
JavaScript. JSX makes the code:

• More readable and expressive.


• Easier to understand and debug.
4. One-Way Data Binding
React uses one-way data binding, meaning data flows in a single direction from
parent components to child components via props. This provides better control over
data and helps maintain predictable behavior.
5. State Management

React manages component state efficiently using the useState hook (for functional
components) or this.state (for class components). State allows dynamic updates
without reloading the page.

• React vs Angular
React Angular

React is a JavaScript library Angular is a JavaScript framework

React uses one-way data binding, Angular uses two-way data binding
React Angular

React uses JSX (JavaScript XML) Angular uses HTML templates with special
for templating. Angular directives.

React uses the Virtual Dom


Angular used the Real Dom concept
concept

History of React

• React was developed by Facebook in 2011 to improve the performance of their


applications and was officially released as an open-source library in 2013.

• It was designed to create dynamic, fast, and responsive user interfaces for
web applications by focusing on the view layer.
• React introduced concepts like components (reusable UI pieces) and the
virtual DOM (a lightweight copy of the real DOM) for optimizing UI
updates.
• React is now a widely used framework for building modern web and
mobile apps, supported by a strong community and major companies.

❖ ReactNative and Vue


Feature React Native Vue.js

Framework for building JavaScript framework for


Type
native mobile apps building web user interfaces

Developed Evan You (independent


Meta (formerly Facebook)
By developer)

Release Year 2015 2014

Platform
iOS, Android (Mobile apps) Web (primarily browsers)
Target
Programmin JavaScript (with JSX), JavaScript, TypeScript
g Language supports TypeScript supported

UI Rendering Native UI components Virtual DOM rendering

Performance Near-native performance Depends on web rendering


performance
Feature React Native Vue.js

State
Redux, Context API, MobX Vuex, Pinia
Management

Component Functional components


Single File Components (SFCs)
Structure with hooks

Community
Very large and active Large and growing community
Support
Mobile application
Use Case Web application development
development

Popular I n stagram,
Alibaba, Xiaomi, GitLab
Companies Using Facebook, Airbnb

❖ React Environment Setup


To run any React application, we need to first setup a ReactJS
Development Environment. In this article, we will show you a step-by-
step guide to installing and configuring a working React development
environment.
We will discuss the following approaches to setup environment in
React.
Pre-requisite:

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

• Installation of Node.js on Windows


• Installation of Node.js on Linux
• Installation of Node.js on mac
Method 1: Using create-react-app (CRA command)
Step 1: Navigate to the folder where you want to create the project and
open it in terminal

Step 2: In the terminal of the application directory type the following


command npx create-react-app <<Application_Name>>
Step 3: Navigate to the newly created folder using the command cd
<<Application_Name>>
Step 4: A default application will be created with the following project
structure and dependencies
v MY-APP v my-app >

node_modules v public
# Favicon, ico O index.html
logo19Z,png logo51Z.png l)
maniFest.json =■ robots.txt v
src
# App.css JS App.js
JS App.test.js

# index.css JS index.js *■
logo,svg
JS reportWebVitalsJs Js
setupTestsjs .gitignore
{} package-Lock.json {}
packagejson |® README.md

Application structure
It will install some packages by default which can be seen in the dependencies in
package.json file as follows:

"dependencies": {
"@testing-library/jest-dom": "A5.17.0",
"@testing-library/react": 'A 3.4.0",
"@testing-library/user-event": 'A 3.5.0",
"react": "A18.2.0",
"react-dom": "A18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "A2.1.4"
}

Step 5: To run this application type the following command in terminal


npm start
Step 6: The following output will be displayed in the browser
♦>Create an app using create-react-app

Create a New React App - npx create-react-app


Steps to Create a React App Using npx create-react-app Step 1: Install Node.js
and NPM
The first step is to install Node.js in your system to create a React application.
Step 2: Initialize the React App Using create-react-app
If you have installed an npm version greater than or equal to 5.6, you can use the
following npx command to create a new React app:
npx create-react-app app_name

If you are using npm version 5.1 or less, you cannot use the npx command, you
need to install the create-react-app globally by using the command
npm install -g create-react-app
create-react-app app_name
Step 3: Switch to the project directory

Once the project is created switch to the project directory using the following
command:

cd app_name
Step 4: Start the development server
To run the app, use the following command. This command will locally run your
app. npm start
React Project Structure
The project structure of your React application will look something like this
• src: This folder contain all the necessary source code of the project.
• public: This folder stores the HTML files and the assests.
• node_modules: Dependencies of the project.
• package.json: Used dependencies and scripts information.
• README.md: Any additional information for documentation.

npx create-react-app my_app


Dependencies in the package.json file
"dependencies": {
"@testing-library/jest-dom": "A5.17.0",
"@testing-library/react": 'A 3.4.0",
"@testing-library/user-event": 'A 3.5.0",
"react": "A18.2.0",
"react-dom": "A18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "A2.1.4"
},
Now Let's modify our react application by making some changes in App.js file
// Filename - App.js import React from 'react';

function App() {
const headingStyle = { color: 'green', textAlign: 'center'
};

return <h1 style={headingStyle}>Welcome To PARUL UNIVERSITY !</h1


>;
}

export default App;

♦> Understanding basics of react app


Create a New React.JS Project
1. Install Vite and Create a Project
npm create vite@latest my-react-app —template react Replace
my-react-app with your desired project name.
2. Navigate into your project directory cd my-react-app
3. Install dependencies: npm install

4. Start the development server:


npm run dev
This will launch the app in your browser at http://localhost:3000.
Understanding the Project Structure:
. public/index.html: The single HTML file where your React app
will be rendered.
. src/index.js: The JavaScript entry point for your React
application.
. src/App.js: A basic React component that serves as the
starting point for your app.
For example, we have implemented a basic react app
import React from 'react';

function App() { return (


<div className="App">
<h1 style={
{ textAlign: 'center' }
}>

Hello, World!
</h1>
</div>
);
}

export default App;

Output:

Hello, World!
Understanding JSX
• JSX stands for JavaScript XML, and it is a special syntax used in
React to simplify building user interfaces.
• JSX allows you to write HTML-like code directly inside JavaScript,
enabling you to create UI components more efficiently.
• Although JSX looks like regular HTML, it’s actually a syntax
extension for JavaScript.
What is JSX?

• JSX combines HTML and JavaScript in a single syntax, allowing


you to create UI components in React.
• It simplifies rendering dynamic content by embedding JavaScript
expressions inside HTML-like tags.
Syntax:
const element = <h1>HeMo, world!</h1>;

• <h1>Hello, world!</h1> is a JSX element, similar to HTML, that


represents a heading tag.
• JSX is converted into JavaScript behind the scenes, where React
uses React.createElement() to turn the JSX code into actual HTML
elements that the browser can understand.
Why Use JSX in React
JSX provides several advantages when working with React:

• Declarative UI: JSX allows you to write HTML-like code directly in


your JavaScript files. This makes it easier to visualize how your
components will render and simplifies the UI development process.
• Cleaner Syntax: JSX is cleaner and more concise than manually
using React.createElement() for each element. It reduces the amount
of boilerplate code and makes components more readable.
• Dynamic Content: JSX makes it easy to embed dynamic content
within your UI. JavaScript expressions can be placed inside {}
within JSX tags, allowing for dynamic rendering of data and
content.

How JSX Works

• When React processes this JSX code, it converts it into JavaScript


using Babel.
• This JavaScript code then creates real HTML elements in the
browser’s DOM .
• \which is how your web page gets displayed.
JSX Transformation Process

• Writing JSX: Write JSX just like HTML inside JavaScript files (React
components).
const element = <h1>HeUo, World!</h1>;

• JSX Gets Transformed: JSX is not directly understood by browsers.


So, it gets converted into JavaScript by a tool called Babel. After
conversion, the JSX becomes equivalent
to React.createElement() calls. After transformation JSX becomes.
const element = React.createElement('h1', null, 'Hello, World!');

• React Creates Elements: React takes the JavaScript code


generated from JSX and uses it to create real DOM elements that the
browser can render on the screen.
How to Implement JSX in Action

JSX can be implemented in a React project to create dynamic and


interactive UI components. Here are the steps to use JSX in a React
application:
• Create a React App: If you don’t have a React app yet, create one
using Create React App:
npx create-react-app jsx-example cd jsx-example npm start
. Write JSX in the Component: In the src/App.js file, write JSX to
display a message:

import React from "react"; function App() {


const message = "Hello, JSX works!";

return <h1>{message}</h1>;
}

export default App;


Output:

Hello, JSX
works!
• The JSX code <h1>{message}</h1> will be transformed into
JavaScript by Babel. Then react will then create a virtual DOM
element for the <h1> tag with the text inside. and this virtual
DOM is then used to update the actual browser DOM, displaying
"Hello, JSX works!" on the screen.
• After React processes the JSX, it renders the message on the
screen.

Uses of JSX

Here are some significant uses of JSX:


1. Embedding Expressions
JSX allows you to embed JavaScript expressions directly within the
HTML-like syntax.
2. Using Attributes in JSX
In JSX, attributes are specified similarly to HTML, but with some
differences. Since JavaScript is used alongside JSX, certain
attribute
names are written in camelCase instead of the lowercase syntax used in
HTML.
3. Passing Children in JSX

In JSX, components or elements can accept children just like HTML


elements. Children are nested elements or content that are passed into
a component. This allows for flexible and reusable components.
4. JSX Represents Objects

JSX is not directly rendered as HTML by React; instead, it gets compiled


into JavaScript objects representing virtual DOM elements. These
objects are later used by React to efficiently update the real DOM.
* Understanding virtual DOMS
What is the Virtual DOM?
The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM
(Document Object Model). It helps React manage UI updates more efficiently by
keeping a virtual version of the UI in memory. When changes occur, React updates
only the necessary parts of the real DOM, instead of rerendering everything.
How Does the Virtual DOM Work?
Here's a breakdown of how the Virtual DOM works:
1. Rendering the Virtual DOM: React creates a virtual representation of the UI as a
tree of JavaScript objects.
2. Updating State: It generates a new Virtual DOM tree to reflect the updated state
when the application state changes.
3. Diffing Algorithm: React compares the new Virtual DOM tree with the previous
one using its efficient diffing algorithm to identify the minimal set of changes
required.
4. Updating the Real DOM: React applies only the necessary changes to the
real DOM, optimizing rendering performance.
Key Features of React’s Virtual DOM
1. Efficient Updates: By minimizing direct interactions with the real DOM, React
significantly reduces rendering time.
2. Reconciliation Process: React’s reconciliation efficiently updates the UI based
on changes in the Virtual DOM.
3. Batching Updates: Multiple state updates are batched into a single re-render
cycle, avoiding unnecessary computations.
4. Cross-Browser Consistency: The Virtual DOM standardizes behaviour across
different browsers, ensuring consistent rendering.
5. Component-Based Architecture: Virtual DOM integrates seamlessly with
React’s component-based architecture, promoting modular and reusable
code.

* Single-page apps
Step 1: Set Up Your Development Environment
Before you start building your React SPA, you need to set up your
development environment.
1. Node.js and npm: Node.js is a JavaScript runtime environment,
and npm (Node Package Manager) is essential for managing your
project dependencies. You can download and install them from
the official Node.js website.
2. Create React App: Facebook’s Create React App is a tool that
sets up a new React project with a standard structure and
configuration. To install it, run the following command in your
terminal:
npx create-react-app my-react-spa 1. Code Editor: An IDE or code
editor like Visual Studio Code is recommended for writing and
managing your code efficiently.
Step 2: Structure Your React Project
Once your React app is created, you’ll see a directory structure
like this:
my-react-spa/
-node_modules/
-public/
-src/
-App.css
-App.js
-App.test.js
-index.css
-index.js
-logo.svg
-.gitignore
-package.json
-README.md
-yarn.lock

Here’s a simple example of a component:


javascript
// src/components/Header.js
import React from 'react'; function Header() { return (
<header>
<h1>Welcome to My React SPA</h1>
</header>
);
}
export default Header;
// src/App.js
import React from 'react';
import Header from './components/Header';

function App() { return (


<div className="App">
<Header />
<p>This is a simple React single page application.</p>
</div>
);
}

export default App;


Step 4: Add Routing // src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from
'react-router-dom';
import Header from './components/Header'; import Home from
'./components/Home'; import About from
'./components/About';

function App() { return (


<Router>
<div className="App">
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
}

export default App;


Step 5: Style Your Application /* src/App.css */
.App {
text-align: center;
}

header {
background-color: #282c34; padding: 20px; color: white;
}

Step 6: Fetch Data from an API


Most web applications need to fetch data from a server. You can
use the Fetch API or a library like Axios to make HTTP requests
in your React SPA.
Install Axios: npm install axios Fetch data in a component:
javascript
// src/components/Home.js
import React, { useState, useEffect } from 'react'; import axios
from 'axios';
function Home() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => { setData(response.data);
})
.catch(error => {
console.error('There was an error fetching the data!', error);
});
}, []);

return (
<div>
<h2>Home Page</h2>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default Home;


Step 7: Deploy Your React SPA
Finally, you need to deploy your React single page app. Popular
choices for deployment include Vercel, Netlify, and GitHub
Pages. For example, to deploy your app to GitHub Pages:
1. Add the homepage field to your package.json file: json
“homepage”: “https://username.github.io/my-react-spa”,
1. Install the gh-pages package: bash
npm install gh-pages
1. Add deployment scripts to your package.json: json
“scripts”: {
“predeploy”: “npm run build”,
“deploy”: “gh-pages -d build”
}
1. Deploy your
app: bash
npm run deploy

Functional Components vs Class Components


Here is a detailed comparison of Functional Components
and Class Components based on various features.
Functional
Class
Compone
Feature Components
nts

State It can use Hooks It uses this.state


Managem like useState, and this.setState()
ent useReducer

It uses traditional
lifecycle methods
It like
uses useEffect H componentDidMoun
ook for lifecycle t,
methods componentWillUnm
Lifecycle
Methods ount

Returns JSX Uses a render()


directly inside the method to
Rendering function return JSX

Faster and more Slightly heavier due


Performan lightweight due to to the overhead of
simpler structure class instances
ce
Functional
Compone Class
Feature nts Components

Can use React Cannot use hooks;


hooks (useState, relies on lifecycle
useEffect, etc.) methods and state
Hooks
Uses this to
This Does not use this
access props and
Keyword keyword
state

More boilerplate
Less boilerplate
Code code, especially
code, easier to write
for state and
Complexit and understand
methods
y

Requires method
Simple and direct
binding for event
Event event handling
handling
Handling

You might also like