React
React
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.
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>
);
};
};
Export default App;
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;
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.
Constructor (props) {
Super (props);
This.state ={
Count: 0,
};
}
Increment = () => {
This.setState ({count: this.state.count ++1});
};
Decrement = () => {
This.setState ({count : this.state.Count -1});
};
ChildComponent.js
Import React from ‘react’;
Const ChildComponent = (props) => {
Return (
<div>
<p> {props.message} </p>
</div>
0;
};
Export default ChildComponent;
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);
this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {
count : prevState.count + 1,
})));
}
render() {
return (
<div>
<p> Count : {this.state.count} </p>
<button onClick ={this.handleIncrement} > Increment
</button>
</div>
);
}
}
export default MyComponent;
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 = () => {
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>
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() {
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
ComponentDidMount(){
This.myInput.Focus();
}
Render() {
Return (
<input
Type= “text”
Ref = {(input) => {this.myInput – input;}}
/>
);
}
}
Example: -
Import React, ,useRef, useEffect- from ‘react’;
Function MyComponent () {
<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>
<ul>
<Li> Hello 1 </Li>
<Li> Hello 2 </Li>
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;
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;
Home.js
Import React from ‘react’;
Const Home = () => {
Return (
<div>
<h1> Welcome </h1>
</div>
);
};
Export default Home;
Dashboard.js
Import React from ‘react’;
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.
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);
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.
Example: -
Import React, ,useState- from ‘react’;
Const ToDoList = () => {
Const [tasks, setTasks] = useState ([]);
Const *inputValue, setInputValue+ = useState (‘ ‘);
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
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) }
Example: -
Here is the step-by-step explanation with example of using
Portals in React.
);
}
}
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>
);
}
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;
Return (
<div>
{books.map ((book) => (
<div key = {book.id}>
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”.
Example: -
Import React from ‘react’;
Class ButtonComponentextends React.Component {
Render() {
Return {
<div>
<button onClick = {this.handleClick}>Click Me </button>
</div>
);
}
}
Export default ButtonComponent
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;
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;
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.
Example: -
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: -
Example: -
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”.
Example:-
Class MyComponent extends React.Component {
………………………
}
}
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: -
//Embedding Variables
<h1> {greeting}, {name} </h1>
//Embedding Expressions
<p> {2+2} </p>
//Conditional Rendering
,name === ‘Pawan’ ? <p> Welcome</p>
</div>
);
};
Export default ExampleComponent;
Example : -
Suppose you have a array of items that you want to render in
list using React:
Const items = [
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
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
Example:-
Let’s create simple stateless Functional components that
displays a “Hello, *name+’ message:
};
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: -