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

React

Uploaded by

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

React

Uploaded by

mayur jagdale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

React - Content

1. Introduction to React
A popular JavaScript Library for creating user interfaces (UIs)
for web applications is called “React”. It was created by
Facebook and published in 2013. It has now become one of
the most used frameworks for creating dynamic and
interactive user interfaces.
It promotes the use of components-based design,
which simplifies the management and maintenance of
complicated user interfaces by dividing them into smaller,
reusable components.
The virtual Dom (Document Object model) of React is one
of its unique features. The virtual Dom serves as a link
between the state of the application and the rendering
engine of the browser. It is a simplified copy of the real DOM.
React Offers the capabilitiesand flexibility, required to
create a beautiful and effective UIs whether you are
developing a small personal projects or a large scale business
applications.

2. How much JS do you need....???


You should have a solid knowledge of a few important
JavaScript principles before entering directly into React.
Here are some important topics…..
Variables
Data Types
Function
Array and Objects
Classes
Call-back and Promises
Modules
Asynchronous Programming
Template Literals

3. Components
A React Components is a reusable, modular design part
included in the React JavaScript Frameworks, which is mainly
used to create user interfaces. It represents many elements
of applicationsor webpages by combining logic and render.
We have two types’ components, for giving developers
the ability to handle UI components effectively and have a
clean, well-organized codebase.

i. Functional Components
ii. Class Components

i. Functional Components
Functional Components is the simpler way to define
components. It is referred to as JavaScript functions because
they receive input from props and output – JavaScriptXML –
component to display user interfaces.
Example: -
Import React from ‘react’;
const Greeting = (props) => {
return (
<div>
<h1> Hello, {prop.name} </h1>
<p> Welcome </p>
</div>
);
};

Const App = () => {


Return (
<div>
<Greeting name = “Pawan”/>
<Greeting name = “Preet”/>
</div>
);

};
Export default App;

# “Greeting” is the functional component which takes


“name” prop and renders a simple greeting message with the
provided name.
# “App” component uses “Greeting” to pass from the two
different names as props to render multiple greeting on the
page.

ii. Class Components


React allows you to define components using ES6 classes by
using class components. They enable higher-level
functionality like lifecycle techniques and state management.
Example: -
import React, ,Component- from ‘react’;
class Welcome extends component {

constructor (props) {
super (props);
this.state = {

message : Welcome;
};
}
Render () {
Return (
<div>
<h1> Hello, {this.props.name} </h1>
<p> {this.state.message} </p>
</div>
);
}
}
Const App = () => {
Return (
<div>
<Welcome name = “Pawan”/>
<Welcome name = “Preet”/>
</div>
);
};
Export default App;

“Welcome” is the class Component.

“state” object contains the “message” property with


the value “welcome”.

“render” Components have to use “render” function,


which return the JSX template for the component’s UI.

4. Intro to JSX
JSX or JavaScript XML is a JavaScript syntax extension that is
largely used in React, a well-liked toolkit for creating user
interfaces. JSX makes it simpler to construct and work with
the UI components of web applications by allowing
developers to write HTML-like code right within their JS files.
Developers may more easily and openly describe the
structure of the user interfaces with JSX. JSX allows
developers to express UI components and their
characteristics using well known HTML tags and attributes
rather than lengthy, imperative JS code.
A compiler like Babel is used to internally translate JSX
into ordinary JS code. Through this transformation, JSX
components are converted into React-compliant function
calls or object representation that may be shown on a
webpage.

5. State and props


State: - A “state” in React is a way for component to keep
tracks of and control its own data. It reflects the existing
state or values, which may alter over time and have an
impact on how the component behaves.
It automatically re-renders a component as its state changes,
altering the user interfaces to reflect the new state.
Example: -
Code – 1…….
Import React, ,Component- from ‘react’;
Class Counter extends Component {

Constructor (props) {
Super (props);
This.state ={
Count: 0,
};
}
Increment = () => {
This.setState ({count: this.state.count ++1});
};
Decrement = () => {
This.setState ({count : this.state.Count -1});
};

“Counter” component that keeps its original “count”


value of zero.

Also, we have two ways of modifying the state:


increment and decrement.

The “increment” function is invoked when the user hits


the “increment” button, and it updates the count state
by adding 1 by using the “setState” method offered by
React.

The “decrement” method is invoked when the user


selects the “Decrement” button, and it changes the
count state by subtracting 1.
Code – 2……..
Render() {
Return(
<div>
<h2> Counter : {this.state.count} </h2>
<button onClick = {this.increment}> Increment </button>
<button onClick = {this.decrement}> Decrement</button>
</div>
);
}
}
Export default Counter;
React immediately re-renders the component since the
state has changed, and the revised count value is
represented in the UI.

Props:- The term “props” in React refers to “properties” and


it is a method for transferring data from a parent component
to child component. A child component cannot directly edit
the data it gets through props since they are read-only. This
makes the application more dependable and simpler to
maintain by providing a unidirectional flow of data
throughout the React component tree.
Due to their ability to make components reusable and
customizable, props are a key React motion. You may alter a
component’s behaviour and look by passing it various props.
Example:-
In our Example, a Parent Component name “Parent
Component” renders a child component named “Child
Component”. This child component shows the message that
was sent to it as a prop by the parent component.
Parentcomponnet.js
Import React from ‘react’;
Import ChildComponenet from ‘./ChildComponent’;

Const ParentComponent = () => {


Const message = ‘Hello From ParentCompo’;
Return (
<div>
<Child Component message = {message} />
</div>
);
};
Export default ParentComponent;

ChildComponent.js
Import React from ‘react’;
Const ChildComponent = (props) => {
Return (
<div>
<p> {props.message} </p>
</div>
0;
};
Export default ChildComponent;

Using the message “prop” with the value “Hello from


ParentCompo” the “Parent Component” render the
“Child Component” and passes it.

This prop is delivered to the “Child Component”


through the function arguments (“props”) and displayed
inside the paragraph (“<p>”) element.
Important:- It’s very important to keep in mind that props
are not just simple data types like strings or integers; they
may also be advanced objects or even functions.
Also properties may have whatever name you choose, letting
you customize the API for your components to suit your
unique requirements.

6. Constructor
A Constructor is a special method in React that is called when
a new component is created. It is a part of the component’s
lifecycle and is used for setting up the components state,
binding event handlers, and doing any other setup work
required before the component is rendered to the screen.
Constructor are not usually required in more recent version
of React (16.3 and later), since you may directly initialize the
state using the class field syntax. However, they can still be
helpful in some circumstances, such as when directly binding
event handlers or carrying out a setup that needs more
complex reasoning.
Example: -
Import React, ,Component- from ‘react’;
Class MyComponent extends Component {

constructor (props) {
super(props);

// Initialize state in the constructor


this.state = {
count = 0
};

this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {

// Updates Stat ewhen the button is clicked


this.setState (( prevState => ({

count : prevState.count + 1,
})));
}

render() {
return (

<div>
<p> Count : {this.state.count} </p>
<button onClick ={this.handleIncrement} > Increment
</button>
</div>
);
}
}
export default MyComponent;

if you’re using a more current version of React, keep in


mind that you might not rquire a constructor for this
specific example because eyou can initialize the state
directly using class fields like this:
Example: -
Class MyComponent extends Component {
State = {
Count:0,
};

//The rest of the Component5 stays the same


}

For simple cases like the one shown above, the


components is not required because of the class field
syntax’s automated binding of the event handler
functions to the component instance.

7. Form
A “Form” is an important React Component that is used to
collect and manage user input. Through a variety of form
components, includinginput fields, checkboxes, radio button,
and choose dropdowns, user may enter data. When users
submit a form, the information is often either used within
the applications to start certain activitiesor transferred to a
server for additional processing.
Here is the example of a simple React form with step-by-step
explanation.
Example: -
Step – 1
First, we create a functional component for our form, We call
it ‘LoginForm’.
The “useState” hook is used by “LoginForm” component to
keep form fields states updated. It sets the ”FormData”
state’s “username” and “password” fields to empty values.

Codes: -
Import React, ,useState- from ‘react’;
Const LoginForm = () => {

Const [Form Data, setFormData] = useState 9{


Username: ‘ ’,
Password: ‘ ’,
});

Step – 2
The “onchange” event of the input fields is handled by the
“handleChange”function. This method uses the spread
operator to preserve the old values while updating the
“FormData” state with the new values as the user fills in the
input fields.

Code: -
Const handleChange = (event) => {
Const {name, value} = event.target;
setFormData({
…Form Data,
[name]: value,
}));
};

Step – 3
The “onSubmit” event of the Form is handled by the
”handleSubmit” function. This function is invoked whenever
the user clicks the “Submit” button or hits enter. The
“event.preventDefault()” function stops the default form
submission behaviour. For demonstration reasons, it logs the
Form data to the console instead.
Code: -
Const handleSubmit = (event) => {

Event.preventDefault();
Console.log (‘Submitted’, FormData);
};

Step – 4
The “return” statement’s “Form” section uses JSX to build
the form. The “<input>” element is used to construct the
“username’ and “password” input fields. To record user input
the “onChnage” event is assigned to the “handleChange”
function, and the value attribute of each input field is set to
the relevant state in “FormData”.

Code: -
Return(
<Form onSubmit = {handleSubmit}>
<div>
<label html For = “username”> Username: </label>
<input
Type = “text”
Id = “username”
Name = “username”
Value = {FormData. username }
onChnage = {handleChange}
/>
</div>
<div>
<label html For = “password”> Password: </label>
<input
Type = “password”
Id = “password”
Name = “password”
Value = {FormData. username }
onChnage = {handleChange}
/>
</div>

<button type = “submit”> Submit </button>


</Form>
0;
};
Export default LoginForm;

8. Conditional Rendering
In React, conditional rendering is the process of rendering
certain elements or components depending on
circumstances or states. It enables you to modify your React
application’soutput based on a variables, including user
interactions, dynamic data, and other elements. You may
make user interfaces that are more dynamic and interactive
by conditionally rendering the components.
React commonly uses JavaScript expression or ternary
operators within JSX (JavaScript XML) code to implement
conditional rendering. Declaratively writing React component
is made simple by JSX’s ability to blend JavaScript with HTML-
like syntax.

Example: -
Assume that we have a straightforward React component
that shows a greeting depending on the time of day. We
want to display “Good Morning” message if it’s the morning
and a “Good Afternoon” message it’s the afternoon.
Code: -
Import React from ‘react’;
Class Greeting extends React.component {
Constructor (props) {
Super (props);
This.state = {
timeofDay:newData().getHours()’
};
}
The “Greeting” class component is one that we have.
We set the “timeofDay” variables, which denotes the
current hour of the “day” in the constructor of the
object.

Code: -
Render() {

Const {timeof Day} = this.state;

Let greeting message;


If (timeofDay >= 12) {
greetingMessage = ‘Good Afternoon’;
} else {
greetingMessage = ‘good Morning’;
}

Return (
<div>
<h1> {greetingMessage} </h1>

</div>
0;
}
}
Export default Greeting;
The “greetingMessage” is chosen based on the
“timeofDay” using a JavaScript “it….else statement” in
the “render” function. We set “greetingMessage” to
“Good Afternoon” if it’s afternoon and “Good Morning”
otherwise.
9. References
Referencing Dom elements or React component directly in
React is made possible by the “references” (refs)
functionality. It offers a way to obtain a reference to a
specific React application element or component, which can
be helpful for a number of things like focusing on input field,
getting measurement, or integrating with external libraries
that need direct Dom access.
You must first construct refs and then connect to Dom
element or a React component in order to use refs in React.
Referencing can be done in two ways.
i. String refs
ii. Callback refs

Let’s learn about these ways……….

i. String refs: - Before React 16.3, DOM items produced by


components may be referenced using string references. They
had several drawbacks, such as being considered dangerous
for usage in specific circumstances, but they allowed
developers to interact and alter these aspects directly. The
definition of a ref attribute with a “callback” function that
took the DOM element as an input resulted in the creation of
string references. They were abandoned in favour of
utilizing the “createRef()” API or the “useRef()” hook, which
offers safer and more dependable ways for React
components to reference and interact with DOM items.
Example: -
class MyComponent extends React.component {
constructor(props) {
super(props);
this.muInput = null;
}

ComponentDidMount(){
This.myInput.Focus();
}

Render() {
Return (
<input
Type= “text”
Ref = {(input) => {this.myInput – input;}}
/>
);
}
}

You could use “string refs” to create a reference in


previous version of React. Due to its drawbacks and
restrictions, the method is currently regarded as legacy
and is not advised for usage in new programs.

ii. Callback refs: - The use of “callback refs” is advised while


creating refs. When a DOM element or component is
mounted or unmounted, a “callback ref” is used to create a
function that will take as an argument the instance of the
element or component. The element or instance is
subsequently saved in a variable and made available within
the component’s scope.

Example: -
Import React, ,useRef, useEffect- from ‘react’;
Function MyComponent () {

Const myInputRef = useRef (null);


useEffect (() => {
muInputRef.current.Focus ();
}, []);
Return (

<input
Type = “text”
Ref= {myInputRef}
/>
);
}
we Create a “ref” called “myInputRef” using the
“useRef” hook. Then we use the ref property to tie this
“ref” to the input element. We access the DOM element
within the “useEffect” hook using “myInputRef.current”
and call the “Focus()” function to focus the input
element and prepare it for user input.

10. Fragments
A “Fragments” in React is a feature that enables you to
combine multiple components without addingadditional
wrapper elements to the DOM.
Normally, you must wrap several items in a single parent
element if you wish components to return more than one
element. By eliminatingthis extra layer in the DOM tree,
fragments allow you to write cleaner, simple code.
In Simple words, Fragments are useful when delivering an
array of items from a component or when you want to return
the nearest elements without adding any extra HTML.
In JSX, we have two types of fragments syntax:
Short syntax and Long Syntax.
Short Syntax

<>
………………………………
</>

Long Syntax
<React.Fragment>
………………………………..

</React.Fragment>

Let’s take an example of Fragments


Example:
Import React from ‘react’;
Const ExampleComponent = () => {
Return (
<>
<h2> Fragment Example </h2>
<p> Hello, Hello, Hello, </p>

<ul>
<Li> Hello 1 </Li>
<Li> Hello 2 </Li>

<Li> Hello 3 </Li>


</ul>
</>
);
};
Export default ExampleComponent;
The example uses a “ExampleComponent”that uses
fragments to return several items. We utilise the
fragments syntax with “<> ………</>” to group the items
together rather than enclosing then in a “<div>” or
other container element.

HTML Part
AS you can see, the usage of fragments has prevented the
final DOM output from containing on additional container
element around these items. It lessons any potential negative
impacts of extraneous wrapper components and keeps the
HTML structure cleaner.

11. Router
A “router” in React is a Framework or Component that
supports client-side routing. The Feature enables you to
handle various URLs and render various components
depending on the current URL or route. In single-page
applications, when the content changes dynamically without
a full page refresh, router as an important component.
The “react-router” package, which offers a selection of tools
and components to manage routing in a React applications, is
the most common router in React.
For use of router, the first step is install the “react-
router-dom” package. Here is the command for install
this package.
{ npm install react-router-dom }
brackets use for just highlight

Example: -
In this example, we make a basic application which have
navigation bar and it will rendered when we clicked on the
buttons of navigation like Home, Contact, About.
You need to activate the router in your primary
application component, commonly called “App.js”. The
main part of this is Browser Router, which employs the
HTML5 History API to maintain synchronization between
the UI and URL.
App.js
Import React from ‘react’
Import {BrowserRouter as Router, Route, Switch, Link} from
‘react-router-dom’;
// Target or import all three Navigation component here
Import Home from ‘./components/Home’;
Import About from ‘./components/About’;
Import Contact from ‘./components/Contact;
Function App() {
Return (
<Router>
<div>
//Navigation
<nav>
<ul>
<li> <Link to = “/”> Home</Link>
<li> <Link to = “/about”> About</Link>
<li> <Link to = “/contact”> Contact</Link>
</ul>
</nav>

<switch>
//Routing
<Route exact path = “/” Component = ,Home-/>
<Route exact path = “/about” Component = ,About-/>
<Route exact path = “/contact” Component = ,Contact-/>
</switch>
</div>

</Router>
);
}
Export default App;

Three Navigation Components


Our App.js consist of three parts : Home, About , Contact.
When the linked route is active, each of these components
will be displayed.

Home.js – First Component


Import React from ‘react’;

Function Home () {
Return <h1> Home Page </h1>;
}
Export default Home;
About.js – Second Component
Import React from ‘react’;

Function About () {
Return <h1> About Page </h1>
}
Export default About;

Contact.js – Third Component


Import React from ‘react’;
Function Contact () {
Return <h1> Contact Page </h1>;
}
Export default contact;

We have a basic navigation bar with three links in the


App.js file: Home, About and Contact. Any of these links
will update the URL properly and render the right
component when you click on them.
The “Switch” component in “App.js” makes sure that
just the first matched route is rendered and that only
one component is displayed at once.
12. Code Splitting
In order to increase the performance, React applications use
a method called cod splitting, which divides the JavaScript
code that is packaged into smaller units.
Instead of developing the complete applicationscode to the
user’s browser all at once, the idea is to divide the code into
smaller bits and then load only the necessary code when it is
required. Because the browser only needs to download the
code for the current page or component and may get the
remainder as needed, the initial loading time is reduced.
In order to perform code splitting in React, one may use
dynamic imports or tools that handle code splitting
automatically, such as web pack or rollup. Let’s look at a
basic example utilizing dynamic imports to see how code
splitting functions.
Example: -
Consider a React application using the “Home” and
“Dashboard” components. Code Splitting is something we
wish to implement for the Dashboard components.

Home.js
Import React from ‘react’;
Const Home = () => {
Return (
<div>
<h1> Welcome </h1>
</div>
);
};
Export default Home;

Dashboard.js
Import React from ‘react’;

Const Dashboard = () => {


Return (
<div>
<h1> Welcome </h1>
</div>
);
};
Export default Dashboard;
App.js (Without Code Splitting)
Import React from ‘react’;
Import Hoem from ‘./Home’;
Import Dashboard from ‘./Dashboard’;

Const App = () => {


Const showDashboard = true;

Return (
<div>
<Home/>
{show Dashboard && Dashboard />}
</div>
);
};
Export default App;
“Home” and “Dashboard”components are imported at
the start of “Appp.js”. Both parts are contained in the
primary JavaScript bundle when the programme is
packed. Therefore, the user must download its code in
advance even if they access the “Dashboard” page.

Let’s use dynamic imports to accomplish code splitting


so that the “Dashboard” component only loads as
neede.

App.js (With Code Splitting)


Import React, ,useState- from ‘react’;

Const App = () => {


Const [show.Dashboard, setShowDashboard]=
useStae(False);

Const handleClick = () => {


Import (‘./Dashboard’). then (module) = > ,
setShowDashboard (true);
});
};
Return (
<div>
<h1> Welcome </h1>
<button onClick = {handleClick}>Dashboard </button>
{showDashboard && <Dashboard/>}
</div>
);
};
Export default App;
With the code splitting techniques the “Dashboard”
component’s code is not initially loaded when the user
access the home page. Only when a user hits the
“Dashboard” button in the code for the Dashboard
component asynchronously retrieved and shown on the
page. On-demand loading of the “Dashboard”
component and a smaller initial bundle size improve the
speed of the applications.

13. Hooks
For Using state and other react capabilitiesin Functional
Components, React “hooks” are functions. They were made
available in React version 16.8 to allow “stateful” logic to be
written and component behaviour to be reused without the
need for class component.
Before the introduction of hooks, class component were
often used to contain “stateful” behaviour, which might be
time-consuming and result in complicated code structures.
Hooks make this easier by enabling the usage if state and
other React capabilitiesin functional components, which
make them clearer and simpler to understand.
Let’s take an example of most common used hook of React.
useState: -It allows you to add state to functional
component. It returns a state variable and a function to
update that state.
Example: -
Import React, ,useState- from ‘react’;
Function counter () {
Const [ count, setCount ] = useState (0);

Const increment = () => {


setCount (count + 1);
};
Return (
<div>
<p> Count : {count} </p>
<buuton onClick = {increment} > Increment </button>
</div>
);
}
we create state variable “count” using the “useState”
hook, then we use the method “SetCount” to update it.
The component re-renders with the changed value
when the button is clicked, calling the increment
method to update the count state.

Types Of hooks:
Here is the list of commonly used hooks in React.
useState: - It allows you to add state to functional
component. It returns a state variable and a function to
update that state.

useEffect: - Reacts “useEffect” hook enables you to execute


side effects in functional components. It takes the place of
lifecycle methods used by class components, such as
“componentDidMount”, ”componentDidUpdate”,and
“componentWillUnmount”.It is utilised for a activities like
data retrieval, subscriptions, DOM changes, and anything
else that should take place aside from the typical component
rendering.

useContext: - Without having to manually provide props


through each level of the component tree, React’s
“useContext” hook enables you to access the context of a
parent component. Without needing to transfer the data via
each level, context enables component to exchange value,
such as themes, user data, or any global data.

useReduces: - Reacts “useReduces” hook offers an alternate


method for controlling advanced state logic in functional
components. When the state transition is more complex and
contains several sub-values or when you need to execute
some logic before updating the state, it’s frequently used an
alternative to the “useState” hook.

Usecallback: - React has a hook called “useCallback” that is


used for memorizing functions. Avoiding, pointless re-
renders of child component that get functions as props, it’s
very helpful for improving the speed of your component.

useMemo: - React has a hook called “useMemo” that may be


used memorize a computation outcomes. It helps in
increasing the performance of your component by avoiding
needless re-computations of expensively computed
variables.

UseRef;- Reacts “useRef” hook offer a means to build a


mutable reference that remains across component re-
renders. It is frequently used to interact with and access
DOM elements as well as to store values that do not require
re-rendering.

useLayoutEffect: - React has a hook called “useLayoutEffect”


that is quite similar to the hook called “useEffect”. Although
it executes synchronously after all DOM updates, it allow you
to apply side effects in functional components. This might be
helpful if you need to measure elements, manipulate the
DOM or carry out other urgent task before the browser
renders.

useImperativeHandle: - React has a hook called


“useImerativeHandle”that enables a parent component to
communicate imperatively with a child component’s
instance. It frequently works in combination with the
“ForwardRef” function to expose particular child component
methods or attributes to their parent component.
useDebugValue: - React has hook called “useDebugValue”
that is used to troubleshoot custom hooks. It has no effect on
how your hook behaves, but it gives React DevTools more
information, which makes it simpler to investigate custom
hooks which debugging.

14. MVC (Model View Controller)


Model view controller or MVC is a programme design pattern
that is frequently used for creating web applications and
other software system. It divides applicationsinto three
related but distinct parts, each with a different function:
Let’s understand about Model View Controller in parts……
Model: - It represents the application’sdata and business
logic. It controls the data and keeps the view in formed of
any data changes, ensuring that the view is constantly
current.

View: - The application’sappearance and user interfaces are


represented by the view. It is in charge of accepting user
inputs and displaying the data to the user.
Controller: - The model and the view are connected through
the controller. It evaluates user input it gets from the view
and then user input it gets from the view and then changes
the model as necessary.

Let’s understand this concept with simple example of React


applicationswhich is managing to-do-lsit : -

Example: -
Import React, ,useState- from ‘react’;
Const ToDoList = () => {
Const [tasks, setTasks] = useState ([]);
Const *inputValue, setInputValue+ = useState (‘ ‘);

Const handleAddTask = () => {


If (inputvalue.trim() ! == ‘ ‘) ,

setTasks (*…task, inputValue+);


setInputValue (‘ ‘);
}
};
Const handleInputChnage = (e) => {
SetInputValue(e.target.value);
};

Return (
<div>
<h1> To-DO List </h1>
<ul>
{tasks.map((task.index) => (
<li key = {index}> {task} </li>
))}
</ul>
<input type =”text” value ,inputValue-
onChange={handleInputChange}/>
<button onClick = {handleAddTask}> Add Task</button>
</div>
);
};
Export default ToDoList;
the ToDoList component serves as both the view and
controller for our applications. Using the “useState”
hook, it controls the applicationsstate(Model), where
tasks denotes a list of tasks and input values denotes a
text input fields for adding new tasks.

Important: -
The Model: “tasks” array holds thelsit of data.
The view: with the help of an input field and button, the
ToDoList component presents the task as an unordered List
(<ul>) and manages user inputs.
The Controller: the component contains two functions that
deals with adding another task to the list and changing the
input field, respectively. These functions are
“handleAddTask” and “HandleInputChange”.

15. Flux
“Flux” is not built-in idea in React; rather, it is a design
pattern that was created as a means of managing
applications state and data flow in a more systematic and
predictable fashion.
Before the introduction of React is built-in state management
solutions like the context API and Redux, it was made
popular by Facebook as a design for creating scalable and
maintainable apps.
The Flux design strictly enforces a unidirectional flow of data
in an effort to avoid the complicationsthat result from two-
way-data binding.
It is made up of four primary parts: View, Actions, Dispatcher
and Store.
Let’s understand these four parts with example and
explanation…
i. view: -
The user interface that render the applications state and
shoe it to the user, often built using React.
View.js
Class TaskList extends React.Component {
handleAddTask () {
const newRask = this.refs.newTaskInput.value;
Dispatcher.dispatch ({
Type: Taskactions.ADD_TASK’
Task: newTAsk’
});
This.refs.newTAskInput.value= “ ”;
}
HandleReamoveTask (index) {
Dispatcher.dispatch({

Type:TaskActions.REMOVE_task’
Index’
});
}

Render() {
Const task = TaskStore.getTasks();
Return(
<div>
<ul>
{tasks.map((task,index) => (
<li key = {index} >
{task}
<button onClick = {() => this.handleRemoveTask(index)}>
Remove</button>
</li>
))}
</ul>
<input type = “text” ref= “newTaskInput”/>
<button onClick = {() => this.handleAddTask()}>Add Task
</button>
</div>
);
}
}

ii. Action
These are events that the user, itself has set off. Actions are
straightforward JavaScrip0t objects that include details about
the event type and any related payload data.
Action.js
Const TaskActions = {
ADD_TASK : “ADD_TASK”,

REMOVE_TASK : ”REMOVE_TASK”,
};
iii. Dispatcher
The primary hub in charge of assigning tasks to the proper’s
shop. The actions are dispatched to the registered shops
after being received from the views.
Dispatcher.js
Const Dispatcher = {
Dispatch (action) {
TaskStore.handleAction(action);
};
};

iv. Store
The application stat eand action handling logic are kept in
stores. They update their state in response to actions from
the Dispatcher and then emit a change event to inform the
views of the state modification.

Store.js
Const tasks =[ ];
Const TaskStore = {

getTask () {
return tasks;
}
handleAction (action) {
switch (action.type) {
case TaskActions.ADD_TASK:
task.push (action.task);
TaskStore.emitChange ();
Break;
Case TaskActions.REMOVE_TASK:
Task.splice (action.index,1);
TaskStore.emitChange ();
Break;
Default:
// Do Nothing for unrecognized action
Break
}
},
emitChange() {
//Notify the views about the state change
}
//other methods for listening to change events, if needed

How the flow of these four parts work


First, the user interacts with the view triggered an Action.
Second, the action is sent to the Dispatcher.
Third, the Dispatcher forwards the action to the relevant
store.
Fourth, The Store updates their state based on the Action
and emits a change event.
Fifth, the view listens for the change event and updates their
display to reflect the new state.

16. Portals
React portals are a strong feature that lets you render a
component’s children outside of its parent component, in a
distinct area of the DOM (Document Object Model)
structure.
In other words, you are not required to present a child
component in a distinct DOM element that is directly
descended from the parent component. When you need to
render elements outside of the normal DOM flow, such as
modals, tooltip, portals are very powerful.
The followingis the common syntax for buildingportals in
React. # ignore the brackets
{ React Dom.createPortal (child, container) }

child : The react element that you want to render in the


portal.
container: The DOM element where you want to
render the child component.

Example: -
Here is the step-by-step explanation with example of using
Portals in React.

Step – 1 import the required modules:


import React from ‘react’;
import ReactDom from ‘react-dom’;

Step – 2 create a new React Component that uses Portals.


Class PortalExample extends React.components {
Render () {

// This is child component that will be rendered in the portal


Const ChildComponent = (
<div className = “portal-child”>
Portal Child Component
</div>
);

//Using ReactDOM.create portal to create a Portal


Return ReactDOM.createPortal (
Child Component,
Document.getElementByID(‘portal-container’)
// (‘portal-container’)The DOM element to mount the Portal

);
}
}
Step – 3 Define the HTML structure with a container
element for the portal.

Function App() {
Return (
<div>
<h1> Portal Example </h1>
<div>
<p> Inner Context </p>
<div id = “portal-container”> </div>
</div>
</div>
);
}

Step – 4 Render the main component inside the root DOM


element, and also render the “PortalExample” component
inside the container element.
ReactDOm.render (
<React.strictMode >
<App/>
<Portal Example />
</React.strictMode>
Document.getElementByID(‘root’)
);
by displaying its child component “(<div className =
“portal-child”> ….. </div>)” into the DOM element with
the ID portal-container, the “PortalExample” component
builds a portal. As a consequence, even if the content of
the “portal-child” div is still a part of the Reactapplicatin,
it will be presented outside the App component’s DOM
tree.

17. React CSS


React is a user interfaces construction JavaScript library; it
does not directly handle CSS. Instead, the user interfaces is
styled and designed using React and CSS.
JavaScript and JSX, a JavaScript syntax extension that enables
you to write code that resembles HTML, are both supported
by React and may be used to construct reusable UI
components. Complex user interfaces may be created by
combining these elements.
For style these components we have two main options.
i. Inline Styles
ii. CSS-in-JS Libraries

i. Inline Styles: - Using inline styles, you may directly apply


styles to React elements. This means providing the JSX
components with a JavaScript object with style attributes as
a prop.
Example: -
Import React from ‘react’;
Const MyComponent = () => {

Const divStyle = {
Color: ‘Red’,
Fontsize: ‘10px’,
Fontweight: ‘bold’
};

Return (
<div style = {divStyle}>
I am Text with 10px Fon size and red Color
</div>
);
};
Export default MyComponent;

ii. CSS-in-JS Libraries: -


There are libraries that let you include CSS directly into your
JS code. They offer a number of advantages, such as scoped
styling and dynamic styling depending in state and props.
‘styles-component’ is the mainly used component for write
CSS directly.
Let’s take an example : -
Example: -
Import React from ‘react’;
Import styles from ‘styled-component’;
Const StyleDiv = Styled.div
Color: ‘Red’;
Fontsize: ‘10px’;
Fontweight: ‘bold’;
;
Const MyComponenst = () => {
Return (
<StyleDiv>
I am Text with 10px Fontsize and Red Color
</StyleDiv>
);
};
Export default MyComponent;

18. Data Flow in React Application


Data flow in React applicationsdescribes how data is passed
and maintained across various components. For the purpose
of developingeffective and maintainable applications,
understanding how data flow is important.
React follows a “one-way-flow” often referred to as a
“unidirectional data flow”. The indicates that information is
sent via props from parent component to child component.
When data is changes it moves in the reverse direction-
through call-back functions, from child components to parent
components. The strict one-way data flow makes it simpler
to understand how data changes spread across the program
and help to preserve consistency.
Let’s understand with example how data flow in a React
application.
Example: -
Consider simple React applicationsthat show a list of books.
Each book is identified by its author, title, and a button that
says “read”. We also have counter that shows how many
books have been as “read”.

Parent Component : - (App)


The parent component in change of controlling the status of
the book list and the “read” count is the App Component. It
stores the data and passes on it to its child component.
Code: -
Import React, {useState} from ‘react’;

// Here we import our both Child Components…..


Import BookList from ‘./BookList’;
Import ReadCounter from ‘./ReadCounter’;
Function App() {
Const [books, setbooks] = useState([
,id:1, title: ‘Book 1’, author: ‘Author 1’, isRead: false-,

{id:2, title: ‘Book 2’, author: ‘Author 2’, isRead: false-,


,id:3, title: ‘Book 3’, author: ‘Author 3’, isRead: false-,
]);

// Function to handle marking a book as read…..


Const handleMarkAsRead = (bookId) => {
setBooks ((prevBooks)) =>
prevBooks.map((book) =>
book.id ===bookId? ,…book,isRead:true-:book
)
);
};
Return (\<div>
<h1> Book List </h1>
<BookList books= {books} onMarkAsRead =
{handleMarkAsRead} />
<ReadCounter books = {books} />
</div>
);
}
Export default App;

Child Component – 1 (bookList)


The “App” component passes the list of books to the
“BookList” component as a prop, which it then maps over the
render each book’s information.Additionaly, it gets a call-
back method called “onMarkAsRead” which it uses when a
book’s “Mark as Read” button is hit.

Import React from ‘react’;


Function BookList ({books, onMarkAsRead}){

Return (
<div>
{books.map ((book) => (
<div key = {book.id}>

<h3> {book.title} </h3>


<p> Author: {book.author}</p>
{book. Is Read ? (
<p> Done </p>
): (
<button onClick = { () => onMarkAsRead (bookid) } >Mark as
Read </button>
)}
</div>
00}
</div>
0;
}
Export default BookList;

Child Componet – 2 (React Counter)


The “App” component sends the list of books to the
“ReadCounter” component totals the number of books
marked as “read”.

Import React from ‘react’;


Function ReadCounter({books}) {
Const read Count = books.Filter ((book) => book.
isRead).length;
Return (
<div>
<h2> Total Books Read : {readcount}</h2>
</div>
);
}
Export default ReadCounter;

How Data Flow Work in this Book App…..???

The status of the book list and the number of read book
are kept in the “App” component. The
“handleMarkAsRead”method and the books current
state are passed as props to “BookList” component.
The “books” attribute is sent to “BookList” component,
which then maps over the list to render each books
information.
When the “Mark as Read” button is pressed, it also
receives the “handleMarkAsRead”function as props and
calls it.
The “BookList” component executes the
“onMarkAsMethod” with the correct “book Id” when
the “Mark As Read” button for a book is clicked.
Calling the “handleMarkAsRead”method in the “App”
component updates the state of the book list by
marking the right book as read.
The “BookList” component receives the modified books
state once more and the cycle is repeated. The
“ReadCounter” component also receives the updated
book state, enabling it to compute and show the overall
number of books marked as “read”.

19. Handling User Events


React provides a simple and effective approach to
managing multiple user interaction, such as button
clicks, form submission, keyboard inputs, mouse
movements and more Handling user events in React is a
critical component of developing interactive and
dynamic online applications.

Let’s take to step-by-step breakdown of how React


handles fundamental user events, especially the “click”
event on a button.

i. Create a React Component


The First step is to construct a component that contains
the button you wish to handle the click event for,
supposing you have already set up a React application.
Let’s refer to this element as “Button Component”.

Example: -
Import React from ‘react’;
Class ButtonComponentextends React.Component {
Render() {
Return {
<div>
<button onClick = {this.handleClick}>Click Me </button>
</div>
);
}
}
Export default ButtonComponent

ii. Define the Event Handler


The event handler function that will be called when the
button is clicked must then be defined. Let’s call the
event handler function “handleClick” for the purpose of
this example.

Example: -
Import React from ‘react’;
Class buttonComponentextends React.Component {
handleClick () {
console.log (‘Button Clicked’);
}
Render() {
Return (
<div>
<button onClick = {this.handleClick}> Click Me </button>
</div>
);
}
}
Export default ButtonComponent;

iii. Bind the Event Handler


The “this” keyword context in React class components
event handler function is n ot always connected to the
component instance. We must either bind the event
handler in the constructor or utilize class attribute to
make sure that the “that” keyword refers to the
component instance.
We will use the class property syntax to bind the event
handler.

Example: -
Import React from ‘react’;
Class ButtonComponentextends React.Component {
handleClick = () => {
console.log (‘Button Pressed’);
}
Render () {
Return (
<div>
<button onClick = {this.handleClick}> Click Me </button>
</div>
);
}
}
Export default ButtonComponents;

iv. Handling the event


The “handleClick”function will be called each time the
button is Presses, along with the console message
“Button Pressed”.

20. Types of Events


In the React mainly four different types of events are
present……
i. Mouse Events
ii. Keyboard Events
iii. Form Events
iv. Focus Events
i. Mouse Events
Mouse events are triggered when a user interacts with
elements using a mouse. In the Mouse events seven
different events are present they are like, onClick,
onDoubleClick, onMouseEnter, onMouseLeave,
onMouseDown,onMouseUp, and onMouseMove.

Let’s take an example of one from these types.

Example: - Handling the “onClick” event,

Import React from ‘react’;


Class ClickEventExampleextends React.Component {
handleClick = () => {
console.log (‘ Clicked Button’);
};

Render () {
Return(
<div>
<button onClick = {this.handleClick}>Click Me
</button>
</div>
);
}
}
ii. Keyboard Events
Keyboard events are triggered when a user interacts
with elements using the keyboard. In the keyboard
events three different events are present onKeyDown,
onKeyUp, and onKeyPress.

Let’s take an example one from these types,

Example: - Handling the “onKeyDown” event.

Import React From ‘react’;


Class keyDownEventExampel extends React.Component
{
handleKeyDown = (event) => {_
console.log (‘key Pressesd’, event.key);
};
Render () {
Return (
<div>
<input type = “text” onKeyDown = {this.handleKeyDown}/>
<div>
);
}
}
iii. Form Events
Form events are triggered when a user interacts with
form elements. In the form events two types of events
are present onChange and onsubmit.

Let’s take an example of one from these types.

Example: - Handling the “onChange” event

Import React from ‘react’;


Class FormEventExample extends React.Component {
handleChange = (event) => {
console.log (‘Input value: ‘, event.target.value0;
};
Render () {
Return (
<div>
<input type = “text” onChnage=,this.handleChange- />
</div>
);
}
}

iv. Focus Events


Focus events are triggered when an element gains or
loses focus. In the Focus events two types of events are
present, onFocus and onBlur.
Let’s take an example of one from these types…

Example: -

Import React from ‘react’;


Class FocusEventExampleextends React.Component {
handleFocus = () => {
console.log (‘Input Focused’);
};
Render () {
Return (
<div>
<input type = “text” onFocus = ,this.handleFocus- />
</div>
0;
}
}

21. Lifecycle events in Component


A Lifecycle event in React is a collections of operations that
are called at various points during the life cycle of a
component. You can control what goes on when component
is created, changed or removed using these methods. With
React 16.3 and later existing lifecycle events are separated
into two parts: “Mounting” and “Updating” and
“UnMounting”.

Mounting Phase: - When a component instance is created


and added to the DOM, these methods are invoked.
We have three Mounting Phase which is mainly used:
constructor(), render() and componentDidMount().

i. constructor
When the component is built and initialised, this method is
invoked. It is utilised to bind event handlers and set the initial
state.

Example:-
Class MyComponent extends React.Component {
Constructor (props) {
Super (props);

This.state = {
Count: 0’
};
// Binding Event Handlers
This.handleClick = this.handleClick.bind (this);
}
}

ii. render()
The HTML representation of the component is created by
calling this function which is required. It must be a pure
function which means it can’t interact with the browser or
change component state.

Example: -

Class MyComponent extends React.Component {


………………………
Render () {
Return <div> {this.state.count} </div>;
}
}
iii. componentDidMount()
After the component has been displayed to the DOM this
function is invoked. It is frequently used to carry outside
effects, such as obtaining data from APIs.

Example: -

Class MyComponent extends React.Compnent {


…………………….
componentDidMount () {
fetchData(). Then ((data) => {
this.setState ({data});
});
}
}

Updating Phase: -
When a component is being re-rendered as a result of
changes in props state, these methods are invoked.
The mainly used Updating Phase is “componentDidUpdate”.

i. componentDidUpdate (preProps, prevState)


The component regenerates before calling this function. In
the event that the component state or props have changed,
it enables you to execute side effects.

Example:-
Class MyComponent extends React.Component {
………………………

//Perform some actions when a specific prop changes


ComponentDidUpdate(prevProps,prevState) {
It (this.props.someprop 1 == prevProps.someProp) {

}
}

UnMounting Phase: -
This method is called just before a component is removed
from the DOM.
In the “componentWillUnmount()”is used, which is perform
any necessary clean-up, such as cancelling network, requests
or cleaning timers.
Example: -

Class MyComponent extends React.Component {


………………….
Component willUnMount () {

//Clean-up an Resources like timers or Subscriptions’


}

22. Embedding JS in JSX


Embedding JavaScript in JSX in React is a way to dynamically
render content and logic within JSX elements. JavaScript’s JSX
(JavaScript XML syntax) extensions let you create HTML-like
code in your React components. Before being run in your
React JSX is transpired into standard JavaScript by
programme like babel.
Simply enclose the JavaScript code is curly brackets { } for
inserting it into JSX. This instructs React to analyse and
interpret the material contained within the brackets as
JavaScript. As a result, you are allowed to use variables,
expression and even function calls inside of JSX syntax.
Example: -
Import React from ‘react’;

Const ExampleComponent = () => {


Const name = ‘Pawan’;
Const greeting =’Hello’;
Const getFullName = (FirstName, LastName) => {
Return ‘$,First Name- $ ,Last Name-’;
};
Return (
<div>

//Embedding Variables
<h1> {greeting}, {name} </h1>

//Embedding Expressions
<p> {2+2} </p>

//Embedding Function Call


<p> Full Name : ,getFullName (‘Pawan’)- </p>

//Conditional Rendering
,name === ‘Pawan’ ? <p> Welcome</p>
</div>
);
};
Export default ExampleComponent;

“ExampleComponent” is a functioningcomponent that


we have, we include JavaScript into JSX inside the return
statement:

Embedding Variables: - the “name” and “greeting” are


rendered according to need by the <h1> element, which
contains the ’name’ and “greeting” variables.

Embedding Expression: - In the “<p>” element, the


equation {2+2} will be shown after being evaluated as 4.

Embedding Function call:- With the input “Pawan”, we


invoke the “getFullName” method, and the output is
shown inside the <p> element.

Conditional Rendering: - “Pawan” is the ternary


operators name, right? …. Verifies that the name
variables equals “Pawan” if so, it will display the unique
greeting message; else, the standard greeting message
will be displayed.
23. Keys in React
In React, ‘keys” are unique features that help in
distinguishingdisplayed item from other component in a
collection (like an array of rendered elements). When the
underlying data changes, React reconciliation process uses
the keys as information to quickly update the user interface.
They are essential when presenting dynamic list of items,
such as when rendering an array of components when using
the map() method.

Example : -
Suppose you have a array of items that you want to render in
list using React:

Const items = [

,id: 1 , name : “Item 1”-,


,id: 2 , name : “Item 2”-,
,id: 3 , name : “Item 3”-,
];

Now, you want to create a list of component based on


this array:
Function ItemList () {
Const Items = [

,id: 1 , name : “Item 1”-,


,id: 2 , name : “Item 2”-,
,id: 3 , name : “Item 3”-,
];
constrenderItems = items.map((item) => (
<div key = {item.id}>{item.name} </div>
));
Return <div> {renderItem} </div>;
}

we’re creating an array of React elements (in this


example “div” elements) from the items of array using
the “map()” method. Take mote of the “div” elements
key property, which is assigned to each item’s id.
The key property is important because it enable React
to recognize each member in the list separately. React
may utilize the key to quickly update the DOM and keep
track of which elements have changed when the
underlying data changes (For example, when a item is
added, deleted or re-ordered). It might result in
undesired behaviour, such as components not updating
correctly or displaying big lists slowly, if the key is left
OFF or used twice.
24. Higher Order Component
Higher Order Components (HOC) is a design pattern in React
that is used to increase the functionality and reusability of
components. Because it is a pattern that results from the
compositional structure of the library, it is not an official
React feature.
A Function called a “HOC” takes a component as input and
outputs a new component with extra properties or
behaviour. It enables you to increase components
capabilities by wrapping it in another component. HOCs
helpful for cross-cutting issues that can be handled across
multiple parts without repeating the same code, such as
managing authentication, data fetching and conditional
rendering.

Let’s take an example for understand how create and use


Higher Order Component in React:

Example: -
Suppose we want to create a Higher Order Components that
logs the lifecycle events of a component and the props it
receives.
Step – 1 Create the Higher Order Component
withLogging.js

import React from “react’;


const withLoggin = (WrappedComponent)=> {
classwithLogging extends React.Component {
ComponentDidMount () {
Console.log (‘Component $ ,Wrapped
Component.namemounted’-;
}
componentWillInMount () {
console.log (‘component
${WrappedComponent.name}willunMount);
}

Render () {
Console.log (‘Rendering $ ,WrappedComponent.name-
withprops:’, thi.props);
Return <WrappedComponent,…this.props- />
}
}
Return WithLogging;
};
Export default WithLogging;
Step -2 Use the Higher Order Component

Import React from ‘react;


Import WithLogging from ‘./WithLogging’;

Class MyComponent extends React.Component {


Render () {
Return <div> {this.props.message} </div>
}
}

//Wrap MyComponent with the Logging HOC


Const MyComponent With Logging = WithLogging
(MyComponent);

Export default MyComponentWithLogging;

The Wrapped component (‘Wrapped Component’) is


the input for the “WithLogging” function which outputs
a new component (“WithLogging”) that logs different
lifecycle events and properties. But the resulting
“WithLogging” components is class-based, you can also
use React hooks to build Higher Order Components with
function components.

25. Stateless Functional Components


A Function that accepts props as input and output JSX (The UI
representation} is known as a stateless functional
component. It contains a state machine or lifecycle methods
of its own. Functional components are simple, making them
simple to understand, develop and test. Being free off
burden of managing instances and lifecycle makes them
quicker than class components.

Example:-
Let’s create simple stateless Functional components that
displays a “Hello, *name+’ message:

Const Greeting = (props) => {


Return <p> Hrllo, {props.name} </p>;

};
A functional component named “Greeting” has been
defined. The data given to the component is included in
the single props argument that is required. The
component output JSX with a greeting message that
includes the name it obtained from the props.
Now, let’s use this function component in another
component: -

Const App =() => {


Return (
<div>
<Greeting name = “Pawan”/>
<Greeting name = “Preet”/>
<Greeting name = “Singh”/>
</div>
);
};

The Greeting component is being rendered three times


in the “App” component with, various names being
provided as props. The Correct greeting for each name
will be shown when React renders the Greeting
Component.

You might also like