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

React PPT

Uploaded by

ittry415
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

React PPT

Uploaded by

ittry415
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Web Hosting

• Web Hosting is like renting space on the Internet or the web


browser. Web hosting provides a space to keep your
website's data on a server. It is the service that provides
the resources to a website and the necessary
technologies for a website that displays over the
internet. When the user hits any request the request goes to
the server. Their PC connects to the server where the website is
stored, then the server sends the website’s data to the user's
computer which is displayed on the screen and allows them to
view it in their web browsers.
• User may opt for hosting plan such as Shared Hosting, Virtual
Private Server (VPS) Hosting, Dedicated Hosting, and
Cloud Hosting that includes providers Amazon Web Services
(AWS), Google Cloud, etc., WordPress Hosting, among
these GoDaddy is one of the largest and well-known web hosting
provider.
REDUX
In React, the famous State Management library is Redux only.
State Management is some thing which takes care of the changes in any
part of the components/application. i.e. it is a management of a data
state for event handling inside the application
State transfer between components is pretty messy in React since it is
hard to keep track of which component the data is coming from. It
becomes really complicated if users are working with a large number of
states within an application.
Redux solves the state transfer problem by storing all of the states in a
single place called a store. So, managing and transferring states
becomes easier as all the states are stored in the same convenient store.
Every component in the application can then directly access the required
state from that store.
So, Redux is a predictable state container for JavaScript applications. It
helps you write apps that behave consistently, run in different
environments (client, server, and native), and are easy to test. Redux
manages an application’s state with a single global object called Store.
Components of Redux
The 4 primary components of Redux are Actions, Reducers, Store, and
Middleware. Actions describe what changes to the state have occurred,
reducers define how the state is updated based on those actions, the
store holds the entire application state, and middleware allows for side
effects like async operations
Actions:
Actions are plain JavaScript objects that describe an event that happened
in the application. They are dispatched to the store, which then triggers
the appropriate reducer to update the state.
Reducers:
Reducers are pure functions that take the previous state and an action as
input and return a new state. They determine how the application's state
should change in response to dispatched actions.
Store:
The store is the central point where the entire application state is stored. It
holds the state, provides methods to dispatch actions, and allows
components to subscribe to state changes, according to Redux
documentation.
Middleware:
Middleware extends the store's functionality by allowing you to add side
effects to the application, such as asynchronous actions or logging. It
intercepts actions dispatched to the store and can perform actions based
on those actions before or after they reach the reducer, according to
Redux documentation
Data Flow in redux
In Redux, data flow is unidirectional. It means data travels in a single
direction from components to the store, which then updates the state
based on actions and reducers
The data flow in Redux follows this pattern: Action -> Dispatch -> Reducer
-> New State -> Store Update -> View (Re-rendering).
• Action: A user interaction triggers an action, which is a plain JavaScript
object representing an intention to change the state.
• Dispatch: The action is sent to the store using the dispatch method.
• Reducer: The store passes the action to the reducer, which is a pure function
that determines how the state should change based on the action.
• State Update: The reducer returns a new state, which the store updates.

• Store Update: The store notifies subscribers (usually components) that the
state has changed.
• Re-rendering: Components read the updated state from the store and re-
render, reflecting the changes in the UI.
Principles of Redux
1.) Single Source of Truth
The state of your whole application is stored in an object tree
within a single-store

2.) State Is Read-Only


The only way to change the state is to initiate an action, an
object describing what happened.

3.) Changes are Made with Pure Functions


To specify how actions transform the state tree, you need to
write pure reducers. The user can start with a single reducer,
and, as the app grows, can split it off into smaller reducers that
manage specific parts of the state tree
React Context API
• Managing state is an essential part of developing applications in React. A common way to
manage state is by passing props. But it can be annoying to pass props when you have to
send the same data to lots of components or when components are far away from each
other. This can make an application slower and harder to work with.
• to pass data down to the component "Child B", we need to pass it down through all the
intermediate components, even if those components don't actually use the data
themselves. This is what is referred to as "prop drilling."
React Context API

• The React Context API is a built-in feature in React that allows you to share data across
the component tree without explicitly passing props down through every level. This
makes it easier to share data between components.

• It's a way to create "global variables" for your application, making it useful for managing
state across deeply nested components without the need for prop drilling.
React Context API
Basically, Context API consists of two main components: the context provider
and the context consumer. The provider is responsible for creating and
managing the context, which holds the data to be shared between
components. On the other hand, the consumer is used to access the context
and its data from within a component.
Creating a Context:
 You use the createContext() function to create a context object. This object has two parts:
a Provider and a Consumer.
 Provider: This component allows you to provide a value to any of its descendant components.

 Consumer: This component is how descendant components can access the provided value.
React Components: function and class
components
In React, components are the building blocks of a user interface.
They are reusable, self-contained pieces of code that represent a
part of the UI. React allows you to break down your UI into
smaller components, which makes it easier to manage and
maintain your codebase.
They can accept inputs called props (short for properties) and
return React elements describing what should appear on the
screen.
There are two primary ways to create components: function and
class components. Each has its own syntax and use cases,
although with the introduction of React Hooks, the gap between
them has narrowed significantly.
Function Components: These are simple JavaScript functions
that take props as input and return JSX elements. They are often
used for presentational or stateless components.
React Components: function and class
components
Class Components: These are ES6 classes that extend
from React.Component or React.PureComponent. [ES6 classes in
JavaScript provide a more organized and familiar way to create objects and handle inheritance,

They have
offering a structured approach to object-oriented programming.]

a render() method where you define the structure of your


component's UI using JSX. Class components are used for
components that need to manage state or have lifecycle methods.
With the introduction of React Hooks, function components gained
the ability to manage state and use lifecycle methods, blurring the
distinction between function and class components.
Component Life cycle
• In React, components have a lifecycle that consists of
different phases. Each phase has a set of lifecycle
methods that are called at specific points in the
component's lifecycle. These methods allow you to control
the component's behavior and perform specific actions at
different stages of its lifecycle.
• A component's lifecycle has three main phases: the
Mounting Phase, the Updating Phase, and the Unmounting
Phase.
• The Mounting Phase begins when a component is first
created and inserted into the DOM. The Updating Phase
occurs when a component's state or props change. And
the Unmounting Phase occurs when a component is
removed from the DOM.
Component Life cycle: Mounting
• The mounting phase refers to the period when a component is being created and inserted
into the DOM.
The mounting phase has three main lifecycle methods that are called in order:

The constructor() lifecycle method

The constructor() method is called when the component is first created. You use it to initialize the component's
state and bind methods to the component's instance.

The render() lifecycle method

The render() method is responsible for generating the component's virtual DOM representation based on its
current props and state. It is called every time the component needs to be re-rendered, either because its props
or state have changed, or because a parent component has been re-rendered.

The componentDidMount() lifecycle method

The componentDidMount() method is called once the component has been mounted into the DOM.
Component Life cycle: Updating Phase

• This phase occurs when a component's props or state changes, and the
component needs to be updated in the DOM.
The shouldComponentUpdate() lifecycle method
The shouldComponentUpdate() method is called before a component is updated. It takes two
arguments: nextProps and nextState. This method returns a boolean value that determines
whether the component should update or not. If this method returns true, the component
will update, and if it returns false, the component will not update.
The componentWillUpdate() lifecycle method
componentWillUpdate() is a lifecycle method in React that gets called just before a
component's update cycle starts.
The componentDidUpdate lifecycle method
The componentDidUpdate() method is a lifecycle method in React that is called after a
component has been updated and re-rendered. It is useful for performing side effects or
additional operations when the component's props or state have changed.
The getSnapshotBeforeUpdate lifecycle method
The getSnapshotBeforeUpdate() method is called just before the component's UI is updated
Component Life cycle: Unmounting
Component Unmounting Phase
The unmounting phase refers to the lifecycle stage when a component is being removed from
the DOM (Document Object Model) and is no longer rendered or accessible.
During this phase, React performs a series of cleanup operations to ensure that the
component and its associated resources are properly disposed of.
The unmounting phase is the last stage in the lifecycle of a React component and occurs
when the component is being removed from the DOM tree.
The componentWillUnmount() lifecycle method
componentWillUnmount(): This method is called just before the component is removed from
the DOM. It allows you to perform any necessary cleanup, such as canceling timers, removing
event listeners, or clearing any data structures that were set up during the mounting phase.
After componentWillUnmount() is called, the component is removed from the DOM and all of
its state and props are destroyed.
Controlled vs Uncontrolled Components
Controlled components in React are the components whose state
and behaviors are managed by React components using states
while the uncontrolled components manage their own state and
control their behaviors with the help of DOM.
Controlled Components
• In React, Controlled Components are those in which form’s data
is handled by the component’s state. It takes its current value
through props and makes changes through callbacks like onClick,
onChange, etc. A parent component manages its own state and
passes the new values as props to the controlled component.
Uncontrolled Components
• Uncontrolled Components are the components that do not rely on
the React state and are handled by the
DOM (Document Object Model).
Building Forms with Controlled Components in React
Generally, when we use forms in a web app, the form state lives inside the
DOM. The whole point of React is to manage the state inside applications
more effectively. We can solve this problem with controlled components.
Controlled Components refer to components that render a form, but the
“source of truth” for that form state lives inside of the component state
rather than inside of the DOM. The reason they are called controlled
components is that React is controlling the state of the form.
const MyForm = () => {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};

return (
<form>
<input id="name" value="{name}" onChange={handleChange} />
</form>
);
};
Reusable React Components
They are pieces of code that can be shared and reused across
different files in your application. It is a modular piece of UI that takes
data from props to build complex and interactive user interfaces.
When creating reusable React components, it's important to keep in
mind two key factors
Avoid side Effects:

• It is not recommended to include logic that interacts with external


data, such as making API calls, directly inside a reusable
component. Instead, you should pass this logic as props to the
component.
. Use Props:

• Props are parameters passed to a component to customize its


behavior and appearance, making it reusable for different purposes.
NodeJS
• Node.js is a powerful, open-source JavaScript runtime environment built
on Chrome's V8 engine.
• It allows you to run JavaScript code outside the browser.
• V8 is a javascript engine. A javascript engine is used to interpret
javascript code to machine code. There are different javascript
engines ex: V8 for chrome, Chakra for IE, Spider monkey for
Netscape etc.
• Google open-sourced the V8 engine and the builders of node.js
used it to run Javascript in node.js.
• nodejs is built on top of V8, which is a runtime environment and
gives javascript the power to run at the server-side
20
NodeJS
• JavaScript is a programming language used in browsers, while NodeJS is a
runtime environment that allows JavaScript to be executed on the server-side.

• JavaScript was earlier mainly used for frontend development. With Node JS,
JavaScript became a backend language as well.
• The V8 engine compiles JavaScript to machine code, making NodeJS fast and
efficient.
• Simplest JS Code: console.log("Hello, World!");
Save this code in file hello.js. With the command node hello.js,
NodeJs executes JavaScript in a server environment or via the command line.

21
Node.js REPL (Read-Eval-Print Loop)
• Is an interactive shell that processes Node.js expressions.
• It reads the code that is input, evaluates it, prints the result, and then
loops to read more code.
• Read : It reads the inputs from users and parses it into JavaScript data
structure. It is then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL,
press ctrl+c twice
• This environment is very useful for experimenting with JavaScript and
Node.js code, debugging, and performing quick calculations.

22
Using the Node.js REPL:

Open your terminal or command prompt.


Type node and press Enter:
$ node
You will see the > prompt indicating that the REPL is ready to accept
commands.

23
• Executing Code:
• Type JavaScript expressions and press Enter to see the results.
• Multiline Expressions:
• Use Shift + Enter to write multiline code
• > function add(a, b) { ... return a + b; ... } undefined > add(5, 10) 15
• Command History:
• Use the up and down arrow keys to navigate through the history of
commands you have entered.

24
• REPL Commands:
• Special commands that start with a dot:
• .help - Displays help for special commands.
• .editor - Enters editor mode for writing multiline code.
• .exit - Exits the REPL.
• .save [filename] - Saves the current REPL session to a file.
• .load [filename] - Loads a file into the current REPL session.
• Using the Editor Mode:
• Type .editor and press Enter
• > .editor
• You will enter a new mode where you can write multiline code. Press Ctrl + D
to execute the code and return to the REPL prompt.

25
NPM (Node Package Manager)
• NPM is a package manager for Node.js packages.
• www.npmjs.com hosts thousands of free packages to download and use.
• The NPM program is installed on your computer when you install Node.js
It is the default package manager for Node.js,
It comes bundled with the Node.js installation.
• Downloading any package in NPM is very easy.
• Open the command line interface and tell NPM to download the package you
want.
• E.g. to download a package called "upper-case“, write
npm install upper-case
• NPM creates a folder named "node_modules", where the package will be placed.
All packages you install in the future will be placed in this folder.
• Once the package is installed, it is ready to use. var uc = require('upper-case');
26
Installing NPM
NPM is installed automatically with Node.js. To check if NPM is installed, and
to verify the installed version, write:
npm -v

Some common NPM commands:


• Initialize a Project:
• Create a package.json file in project directory using the following command:
npm init

• use the -y flag to automatically set up with default values.It answers yes to any
prompys that npm might print on command line.

npm init -y
27
To install a package globally (available across all projects), use the -g flag:
npm install -g <package-name>
• Install Dependencies:
• Install a package, for example, Express, which is a web framework for Node.js:
npm install express
• Uninstalling Packages:

• To uninstall a package and remove it from your package.json file, use:

npm uninstall <package-name>

• Updating Packages:

• To update all the packages to their latest versions, use:


npm update
28
React JS
• ReactJS is most popular Javascript library used for front-end development (build User
Interfaces(UI)) and single page applications.
• React was released first in 2013. It was developed by Jordan Walke, a software engineer
at Facebook, and was initially released as an open-source project on GitHub.
• It was developed and is maintained by Facebook (now Meta).
• It has Component base architecture. Everything is component in React. Components are
independent and reusable bits of code. They are based on DRY.
• Applications are built using reusable components that enable the reload of only the
changed part of the UI. Hence we get a better user experience with React[see the node js
website]
• React is declarative which means that it focuses on what you want to achieve, rather
than how to do it. We describe the desired outcome rather than writing detailed
instructions
React Components
React components are independent, reusable building blocks in a React
application that define what gets displayed on the UI. They accept inputs
called props and return React elements describing the UI.
•Components can be reused across different parts of the application to
maintain consistency and reduce code duplication.

•Components manage how their output is rendered in the DOM based on


their state and props.

•React loads only the necessary components, ensuring optimized


performance.

•Only the specific Component updates instead of the whole page.


Development Environment Settings
• To create react app, we need to download Node.js. Go to its website. Now,
download LTS version as per your OS. It is required because Javascript runs
on web browser but node js helps to run it on system too without browser.
• To check whether it has been installed, open cmd prompt or terminal of
VS Code, type
a) node –v
b) npm
• **Npm is a package manager for JS. It is required because Facebook
created React on node. There is no link to download React. Instead, all the
files create by fb for react were kept on npm server as a package/folder.
• Npm provide us commands using which we can copy the content kept by
facebook on npm website, in our systems.
• We can check for react on npm website by simply typing react there.
• Now, to bring the packages kept on npm, we use npm or npx commands.
• Create a new folder (e.g. React)
• From this folder, Open cmd and write the command:
npx create-react-app reactsam
Here, reactsam is the name of app/website.
*npx keeps installation limited to project and not globally
• With this command the react package from npm server will download in our
system in a new folder react/reactsam. We may Check these files in reactsam
folder
• Now open reactsam in vscode andUse command prompt/terminal of VSCode
now for executing commands.
• Write commands cd reactsam and then npm start. The basic app of react
created by facebook will open through server. A mini local server will be created
and open in our browser at localhost:3000. We need to keep this server on.
• To stop the server, use Ctrl+C. Check by refreshing browser. Server will stop.
• File structure:
• In file README.md, we give all the information about our project. This file
becomes documentation when we upload on github.
• The package.json file is the heart of Node.js system. It is used
to manage project metadata, dependencies, scripts, and various
configurations.
• In public folder, we have index.html. It is used for single page
web app.
Index.js
• src folder has index.js file . This is the file from where
react app starts execution.
• In the first two lines of this file, we import react and
react-dom [already provided by fb] in objects React and
ReactDOM. These files are actually present in node-
modules.
• It also imports index.css file which has universal css code
i.e same for whole website. So it makes sense to import
index.css in index.js as index.js will apply universal css
when it start executing. As a whole, universal css is used
in index.css
• App.js is also imported.
• Next import statement is for report generation
Index.js
• Components are developed in app.js and then imported in index.js and then
rendered with below code. In below code, ReactDom object renders App
component at a div whose id==‘root’. So, the App component is placed at div
with id ‘root’. This div is in index.html which is in public folder.
const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(

<React.StrictMode>

<App />

</React.StrictMode>

);
App.js
• In App.js, we have only one component. One component is written in one file. There are two
import statements that import image and css applicable on the component
import logo from './logo.svg';
import './App.css’;
These two files are also in the src folder. logo.svg contains the logo/image that is displayed when
we execute the project and app.css contains the css specific to component while index.css has
universal css
*Try changing background color or color in app.css and then refresh the browser to see the changes.
• Now, Component can be developed in two ways: using function and using class.
• In app.js, component is developed using function. The function App() is written and this is actually
the component.
• jsx is written inside this function. Html like code is written in js file which is not allowed. So, this
html like code is called jsx.
• The component has the code corresponding to the output i.e. an image <img>, a paragraph <p>
and a link <a>.
• App.js is exported in the last line and imported in index.js. There it is rendered at div with id ‘root’
Summary of Flow
• Component is developed in App.js and its related css is written in app.css. We
import logo and app.css in app.js. We don’t have to link css with app.js. This task
is performed by React.
• A function is written in app.js with the same name as file to create component.
The html like code written inside this function is called jsx.
• This function is then exported.
• Index.js is the main file that first gets executed. It imports react and react-dom.
React-dom has a method render which renders the App component at div with
id=‘root’, which is available in index.html. This can be checked by right click and
inspecting the output in browser. We find header, image, p tag, a tag all inside
root.
• All the files mentioned above have been provided by default by ‘fb’.
• App.js->index.js->index.html->browser
Writing own code
• We write below function in app.js to create component.
import ‘./app.css’;
function App() {
return (
<div className=“app-first">
<h1>First Component</h1>
<p> I like to explore</p>
</div>
);
}
export default App;
• We write classname and not class in jsx. This classname is used in app.css for styling
• To write multiple statements in return, we place them inside a div which acts as a
wrapper. Now, h1 and p act as children of div. This is done because we can return only
one statement in return.

• We export this app and write default with app so that we may change its name when
we import it
Writing own code
• we keep the css of each component separate. In app.css, we write the code below
and import app.css in app.js:
.app-first{
background-color:green;
}

• Now we create index.js and import app.js in it. We write below code:
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('root’));
This code will give the output:
First Component
I like to explore
• our first component is created and passed to index.js which sends it to div with
id=root which is available on index.html.
Writing own code
• App.js will be used as a master/parent component. It will act as path for sending
other components. To avoid mess in src of keeping files of components and their css,
A separate folder ‘components’ will be created inside src folder for all the remaining
components which will be further sent to app.js.
• A Separate file is created for each component.
• Let we create a file FirstSubComp.js. Now, the name of function inside this file would
also be same. This function is called component (like app() function in app.js is a
component). We write below code:
function FirstSubComp() {
return (
<p>This is a sub Component</p>
);
}
export default FirstSubComp;
• Now this new subcomponent is imported in parent component i.e. App.js with below
code:
Import FirstSubComp from ./components/FirstSubComp
Writing own code
Now code of App.js is
import FirstSubComp from ./components/FirstSubComp
function App() {
return (
< FirstSubComp />
);
}
Export default App;

• in return Html tag starts with small letters e.g. h1 while components start with capital
• To write css for the subcomponent, we create css file with same name i.e.
FirstSubComp.css. To add css, we make changes in FirstSubComp
function by adding a class and using same class in css file too.
import ‘./ FirstSubComp.css’ //necessary to mention extension css
function FirstSubComp() {
return (
<p className=“abc”>This is a sub Component</p>
);
}
Overall Flow
SubcomponentApp.js Index.jsindex.html Browser
Props
How to pass data in components is called props
First, in app.js, create variables
import FirstSubComp from ./components/FirstSubComp
function App() {
let ourTitle=“Hello World”;
let ourMoney=10;
return (
<FirstSubComp>
title={ourTitle} //We can even directly write a
string
money={ourMoney} e.g. “Hello World” here
</FirstSubComp>
);
}
Export default App;
We pass the data from app.js
We receive the data passed from App.js through parameters called props. Props is
actually an object and all the data becomes its property. It is not necessary to use
props as the name of object. Some other name may be used too
Code without props
function FirstSubComp() {
return (<div>
<p>This is a sub Component</p>
<h1> 5000 </h1>
</div>
);
}
Code without props
function FirstSubComp(props) {
return (<div>
<p>{props.title}</p>
<h1> {props.amount}</h1>
</div>
);
}
Multiple component
How to attach one component inside another component
To attach a component inside another, simply write:
function FirstSubComp(props) {
return (
<div>
< SecondSubComp />
<div className=“FirstSubComp.css”>
<p>{props.title}</p>
<h1> {props.amount}</h1>
</div>
</div>
);
}
States in React
React components has a built-in state object. To use state, we have to import a function useState() from React library. This
function is also called Reacthook. Hook starts from use keyword.

Import React, {useState} from ‘react’;

Now, we pass a value using this function as follows:

const [title, titleChange]=useState(props.title);

This function returns an array with two values: a variable and a function. So, we do array destructuring. Variable is assigned the
name title and function is assigned the name titleChange.

The state object is where you store property values that belong to the component.

When the state object changes, the component re-renders.


React Myths

Myth 1: “React is a Framework”


It’s a JavaScript library for building UIs, often used for single-page applications. It’s
flexible, and we have to pick your own tools for various aspects.
Myth 2: “React is Only for Complex, Large-Scale Applications”
React.js isn’t just for the big players; it’s equally suited for smaller projects. The
component-based architecture of React ensures better code reusability and
separation of concerns.
Myth 3: “React is too Difficult to Learn Because of JSX”
JSX, or JavaScript XML, is a big part of React. It’s not pure JavaScript. It’s like
JavaScript. JSX actually makes your React code more readable and writeable by
allowing HTML in your scripts.
Myth 4: “React Only Works with Redux”
While Redux is a popular state management tool often used with React, it’s not the
ONLY option out there. In fact, React has its own built-in state management
system. There are also other alternatives like MobX or even the Context API
Myth 5: “React Guarantees High Performance”
Add more
Why React is popular

Easy, Flexible and Simple to Use


React JS allows for interactive UI designs. It follows a component-based approach where
each component has its own controls. This makes the code easily understandable for both
new and experienced developers. Developers who are familiar with JavaScript, HTML, CSS,
and web development will find React easy to use. JavaScript makes it seamless to visualize
the UI within the JavaScript code.
React has a rich library and strong community
React has a rich library and strong community support. React JS boasts a rich set of
component libraries and NPM packages. Developers can take advantage of pre-built
component libraries, allowing them to quickly craft sophisticated UIs without building every
component from scratch. These libraries streamline development, especially under tight
deadlines.
React allows for scalability
A key benefit of using React for building web applications is scalability, which is the ability to
manage complex applications with ease. Using React, software developers can improve the
software application as demand grows.
React employs a modular architecture that enables developers to simplify the application
into smaller components. This ensures easy maintenance and updates over time as changes
occur, without altering the entirety of the software application.
Why React is popular

React enables easy testing


React JS is easier to test than many other front-end frameworks,
enhancing the efficiency of the development process. Software
developers can rigorously test their code before it progresses to the
quality assurance (QA) team, ensuring higher quality and stability. React
enables developers to conduct tests on individual components as well as
complex user interactions within the application
Add more

You might also like