React
React
Course Objectives:
The main objectives of this course are to:
1. To implement the static web pages using HTML and do client side validation using JavaScript.
2. To introduce Node JS implementation for server side programming.
3. To experiment with single page application development using React.
Unit:2 15hours
ReactJS - JSX, ReactJS - components: creating a React component, creating a class component, creating a
function component, ReactJS - styling, ReactJs - properties (props), React Props Validation.
Unit:3 15hours
ReactJS state management, ReactJS event Management, React Constructor, React component API, React
component Life-cycle, React Forms and user input, controlled Component, Un-Controlled Component,
Form link.
Unit:4 15hours
ReactJS - Http client Programming, React Lists, The map() function, React Keys, React Refs, React
Fragments, React Router, ReactCSS, React Animation, React Date picker, DoM in React.
Unit:5 13hours
React AJAX call - HTTP GET request, HTTP GET Request and Looping through data, React Bootstrap,
React Table, React Hooks, React building and deployment.
Text Books
st
1 Learning React: Functional web Development with React and Redux 1 Edition by Alex Banks.
2 The Road to React: your journey to master plain yet pragmatic React.js by Robin Wieruch
Reference Books
1 React.js Essentials: A fast-paced guide to designing and building scalable and maintainable web apps
with React.jsArtemijFedosejev.
2 Full-Stack React projects: Learn MERN stack development by building modem web apps using
MongoDB, Express, React, and Node.js, 2nd Edition paperback by shamaHoque
3 React.js Book: Learning React Javascript Library From Scratch by Greg Sidelnikov
MappingwithProgrammingOutcomes
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10
CO1 S M S M S L M L S M
CO2 S S S S S M S M S M
CO3 S S S S S M S M S M
CO4 S S S S S M S M S M
CO5 S S S S S M S M S M
*S-Strong;M-Medium;L-Low
Unit:1 15hours
ReactJS introduction, why to learn ReactJS, React Environment Setup- pre-requisite for ReactJS, ways to
install ReactJS, ReactJS - Architecture, ReactJS - creating a React Application, React create-react-app,
Features of ReactJS, ReactJS vs Native React, ReactJS
vs AngularJS.
What is React?
React.JS History
The very basic and the most important thing you need to know about React
is the Component. React is nothing but one large pile of big components which
call other small components.
2. Patterns of React
The basic declarative approach is focused on WHAT needs to be done, instead of the
instructions on how it must be done.
Declarative code is useful for making the code more predictable and easier to debug.
With React-based projects, you don’t tell React how to organize the state, you just tell
React ‘I need that state’ and you can rely on React for getting and setting up the state
data. Also, at a higher level, with the help of React, we can achieve global state
management which is typically using some common data logic in the entire system, such
as:
2. Theme Data, or
You can rely on React for efficiently updating and rendering the right components when
the data changes.
Before ReactJS entered the stage, it was very difficult to create dynamic web
applications. ReactJS has simplified this process with the help of a JavaScript Extension
known as JSX. It makes machine-readable codes easier.
And it’s very cool and easy to scale the React application.
3. Backward compatibility
Whenever a new version is updated in React, it only increases the ease of use for us and
the public APIs remain the same. This means we need not worry about updating our
application with any new releases of React as the base APIs remain constant.
This means that you do not have to learn a new version after every update. The old
version remains the same, constant, and compatible with the newly added components.
In a practical context, React 16 maintains the exact same public API as in the (15.x and
earlier) previous versions.
4. Concurrent Mode
Whenever we use an autocomplete form there is a freeze of the cursor at times, mostly
seen in React applications because of its rendering behavior. For example, take a look at
the below diagram. When we try to type “WAIT”, with every key event triggered, UI
gets blocked on updating it
5. SEO Friendly Framework
Search Engines hate heavy JavaScript pages because of reading troubles when the page
is loaded in the browser. Also, if the basic HTML page contains nothing but some meta
tags and script tags, the search engine will assume that our page is blank and the result is
you get a poor ranking.
React has a pre-rendering feature that helps in getting an SEO friendly platform in both
SPAs or multiple page applications.
Also, in React we can achieve server-side rendering very easily in contrast to the older
JavaScript-based applications where we have to make use of external third-party
libraries. Since JS pages are heavy, crawlers take more time to crawl a page, whereas in
React, a page comes as a single web page with the help of Virtual DOM.
Outlined above are just some of the basic React features. There are still tonnes of
advantages of React, covered in the following pointers:
Select “Next”
Destination Folder
Set the Destination Folder where you want to install Node.js & Select “Next”
Custom Setup
Select “Next”
Ready to Install Node.js.
The installer may prompt you to “install tools for native modules”
Select “Install”
Installing Node.js.
Do not close or cancel the installer until the install is complete
Complete the Node.js Setup Wizard.
Click “Finish”
If node.js was completely installed on your system, the command prompt will print the
version of the node.js installed.
If you get a message back saying node was not found, then add it to the path manually:
Adding to the path:
You should not need to do anything to the system variables, as the windows installer
takes care of the system variables itself while installing through the .msi installer.
If you use any other format for installing node.js on your PC, you should put the system
variable path for node.js as follows:
PATH : C:\Users\{username}\AppData\Roaming\npm C:\Program Files\{path to the
nodejs folder}
for example:
PATH : C:\Users\admin\AppData\Roaming\npm C:\Program Files\nodejs
Note: After adding to the PATH, restart the command line, because PATH is only
loaded when initializing new command line sessions.
Step 4: Updating the Local npm version
The final step in node.js installed is the updation of your local npm version(if required)
– the package manager that comes bundled with Node.js.
You can run the following command, to quickly update the npm
npm install npm –global // Updates the ‘CLI’ client
ReactJS – Architecture
React elements
JavaScript representation of HTML DOM. React provides an
API, React.createElement to create React Element.
JSX
React component
React component is the primary building block of the React application. It uses React
elements and JSX to design its user interface. React component is basically a JavaScript
class (extends the React.component class) or pure JavaScript function. React component
has properties, state management, life cycle and event handler. React component can be
able to do simple as well as advanced logic.
eact library is just UI library and it does not enforce any particular pattern to write a
complex application. Developers are free to choose the design pattern of their choice.
React community advocates certain design pattern. One of the patterns is Flux pattern.
React library also provides lot of concepts like Higher Order component, Context, Render
props, Refs etc., to write better code. React Hooks is evolving concept to do state
management in big projects. Let us try to understand the high level architecture of a React
application.
Example
Next, create a file, hello.html and write a simple React application.
<!DOCTYPE html>
<html>
<head>
<title>React Application</title>
</head>
<body>
<div id="react-app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>
<script language="JavaScript">
ReactDOM.render(element, document.getElementById('react-app'));
</script>
</body>
serve ./hello.html
Output
Next, open your favorite browser. Enter http://localhost:5000 in the address bar and then
press enter.
React.createElement
Element tag
Element attributes as object
Element content - It can contain nested React element as well
ReactDOM.render
Used to render the element into the container. It expects two parameters −
React Element OR JSX
Root element of the webpage
Example
<script language="JavaScript">
ReactDOM.render(element, document.getElementById('react-app'));
</script>
Output
Use JSX
Next, let us remove the React element entirely and introduce JSX syntax as shown below
<!DOCTYPE html>
<html>
<head>
<title>React Application</title>
</head>
<body>
<div id="react-app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
ReactDOM.render(
<div><h1>Hello React!</h1></div>,
document.getElementById('react-app')
);
</script>
</body>
</html>
Here, we have included babel to convert JSX into JavaScript and added type="text/babel"
in the script tag.
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
...
...
</script>
Next, run the application and open the browser. The output of the application is as follows
–
By analyzing the application, we can visualize the workflow of the React application as
shown in the below diagram.
Features of ReactJS
Currently, ReactJS gaining quick popularity as the best JavaScript framework among web
developers. It is playing an essential role in the front-end ecosystem. The important
features of ReactJS are as following
o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance
o JSX
JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or
HTML like syntax used by ReactJS. This syntax is processed into JavaScript calls
of React Framework. It extends the ES6 so that HTML like text can co-exist with
JavaScript react code. It is not necessary to use JSX, but it is recommended to use
in ReactJS.
o Components
ReactJS is designed in such a manner that follows unidirectional data flow or one-
way data binding. The benefits of one-way data binding give you better control
throughout the application. If the data flow is in another direction, then it requires
additional features. It is because components are supposed to be immutable and
the data within them cannot be changed. Flux is a pattern that helps to keep your
data unidirectional. This makes the application more flexible that leads to increase
efficiency
Virtual DOM
A virtual DOM object is a representation of the original DOM object. It works like a one-
way data binding. Whenever any modifications happen in the web application, the entire
UI is re-rendered in virtual DOM representation. Then it checks the difference between
the previous DOM representation and new DOM. Once it has done, the real DOM will
update only the things that have actually changed. This makes the application faster, and
there is no wastage of memory.
Simplicity
ReactJS uses JSX file which makes the application simple and to code as well as
understand. We know that ReactJS is a component-based approach which makes the code
reusable as your need. This makes it simple to use and learn.
Performance
ReactJS is known to be a great performer. This feature makes it much better than other
frameworks out there today. The reason behind this is that it manages a virtual DOM. The
DOM is a cross-platform and programming API which deals with HTML, XML or
XHTML. The DOM exists entirely in memory. Due to this, when we create a component,
we did not write directly to the DOM. Instead, we are writing virtual components that will
turn into the DOM leading to smoother and faster performance
Comparison
React.js React Native
Factor
React Native is a
command-line
ReactJS is a
interface tool that
Installation JavaScript library
requires both Node.js
Process installed via the npm
and the React Native
package manager.
CLI to be installed.
React Native
ReactJS components components are
are typically written written in JSX, a
in HTML. These syntax extension of
Components components must be JavaScript. These
imported into the app components are
before they can be compiled directly into
used. native code.
React Native is a
framework used for
developing native
It is compatible with a
mobile apps. It is only
Compatibilit vast range of
compatible with the
y browsers, including
two major mobile
Internet Explorer.
platforms, iOS, and
Android.
React Native is a
better choice for
creating native mobile
ReactJS uses a applications than
Navigation traditional browser- ReactJS. React Native
based approach. relies on native
platform navigational
components.
ReactJS is a good
React Native is a
choice for projects
better choice for
that require high-
Storage projects that need to
performance storage,
be able to scale easily.
such as dynamic web
applications.
React Native is a
React is a framework complete platform
for building that allows building
Platform
applications using native and cross-
JavaScript platform mobile apps
AngularJS ReactJS
Unit:2
ReactJS - JSX, ReactJS - components: creating a React component, creating a class component, creating a
function component, ReactJS - styling, ReactJs - properties (props), React Props Validation.
What is React JSX ?
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript. It
helps us to write HTML in JavaScript and forms the basis of React Development. Using
JSX is not compulsory but it is highly recommended for programming in React as it
makes the development process easier as the code becomes easy to write and read.
JSX creates an element in React that gets rendered in the UI. It is transformed into
JavaScript functions by the compiler at runtime. Error handling and warnings become
easier to handle when using JSX
// Filename - App.js
const element = (
<h1>
Hello,
{name}.Welcome to GeeksforGeeks.
</h1>
);
ReactDOM.render(element, document.getElementById("root"));
Output:
// Filename - App.js
const element = (
<div>
</div>
);
ReactDOM.render(element, document.getElementById("root"));
Output:
Functional Components :
Functional components are simply javascript functions. We can create a functional
component in React by writing a javascript function. These functions may or may not
receive data as parameters, we will discuss this later in the tutorial. The below example
shows a valid functional component in React:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Example
Create a constructor function in the Car component, and add a color property:
constructor() {
super();
this.state = {color: "red"};
render() {
Class Components:
The class components are a little more complex than the functional components. The
functional components are not aware of the other components in your program whereas
the class components can work with each other. We can pass data from one class
component to another class component. We can use JavaScript ES6 classes to create
class-based components in React. The below example shows a valid class-based
component in React:
Example
render() {
Now your React application has a component called Car, which returns a <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example
root.render(<Car />);
There are many ways to style React with CSS, this tutorial will take a
closer look at inline styling, and CSS stylesheet.
Inline Styling
To style an element with the inline style attribute, the value must be a JavaScript object:
render() {
return (
<div>
</div>
);
}
camelCased Property Names
Since the inline CSS is written in a JavaScript object, properties with two names,
like background-color, must be written with camel case syntax:
render() {
return (
<div>
</div>
);
}
JavaScript Object
You can also create an object with styling information, and refer to it in the style attribute
render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
return (
<div>
);
mystyle.module.css:
Create a new file called "mystyle.module.css" and insert some CSS code in it:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Arial;
text-align: center;
}
Import the stylesheet in your component:
App.js:
render() {
index.js:
Props are an important mechanism for passing the read-only attributes to React
components. The props are usually required to use correctly in the component. If it is not
used correctly, the components may not behave as expected. Hence, it is required to
use props validation in improving react components.
Props validation is a tool that will help the developers to avoid future bugs and problems.
It is a useful way to force the correct usage of your components. It makes your code more
readable. React components used special property PropTypes that help you to catch bugs
by validating data types of values passed through props, although it is not necessary to
define components with propTypes. However, if you use propTypes with your
components, it helps you to avoid unexpected bugs.
Validating Props
App.propTypes is used for props validation in react component. When some of the props
are passed with an invalid type, you will get the warnings on JavaScript console. After
specifying the validation patterns, you will set the App.defaultProps.
Syntax:
1. class App extends React.Component {
2. render() {}
3. }
4. Component.propTypes = { /*Definition */};
ReactJS Props Validator
S PropsType Descriptio
N n
Unit:3
ReactJS state management, ReactJS event Management, React Constructor, React component API, React
component Life-cycle, React Forms and user input, controlled Component, Un-Controlled Component,
Form link.
The state is just a fancy term for a JavaScript data structure. If a user
changes state by interacting with your application, the UI may look
completely different afterwards, because it's represented by this new state
rather than the old state.
React applications are built using components and they manage their state
internally and it works well for applications with few components, but when
the application grows bigger, the complexity of managing states shared
across components becomes difficult.
If developers do not have scalability in mind then it is really hard to find out
what is happening when something goes wrong. This is why you need
state management in your application.
Application state management is the process of maintaining knowledge of an application's inputs across
multiple related data flows that form a complete business transaction -- or a session -- to understand the
condition of the app at any given moment. In computer science, an input is information put into the program
by the user and state refers to the condition of an application according to its stored inputs -- saved as variables
or constants.
Core business applications process sensitive information like orders, payments, invoices and bills of material.
This processing depends on the state of the application and results in changes to the balance of inventories,
accounts and financial ledgers. State management allows developers to determine the state of the application
to ensure the changes made appropriately reflect the real-world context and business processes.
There are two accepted models for state management: Front end (also called client side), and back end
In front-end state management, the user's own app or browser maintains the program's state, often by having
certain buttons or UI features enabled or disabled and sending the state along with the message. The user
interface connection ensures the user and the application are in harmony throughout the session.
In back-end state management, an application component will use an external data structure or database to
record the final state when it's done processing activities. Processing the next message will start with retrieving
the previous state from the database. The state variable in the data structure can also synchronize the user
interface -- and through it the user -- with the state of the session.
Early applications controlled the user dialog, so the individual steps within a session were dictated by the
process itself; write data to the user, accept changes, confirm them and commit them. With the advent of web
applications based on the stateless vision of HTML, it became necessary to more clearly define state
management practices.
When a session message -- such as an HTML page -- is received, it is interpreted based on the state, which is
recorded as a variable or constant that every process can access. The record ensures that receiving, for
example, a "confirmation" message while in the "waiting for confirmation" state is handled differently than it
would be in the "waited too long for user response state." That, in turn, ensures that application systems that
update databases and produce durable business records are always synchronized with the real world.
State management is essential in aligning and integrating core business applications and the cloud. Without
some form of state management, business activities as routine as the purchase of something or a request for
information would have to be structured as a single request or response exchange. This could put a significant
burden on the user and would almost certainly reduce the effectiveness of the application. In some cases, such
as the processing of an order, a stateless exchange could hide critical information like current stock levels,
resulting in what could be a significant business impact on the seller and a major inconvenience to the buyer.
Tools
State management tools are typically offered in the form of state management libraries, designed for
developers who want to build state awareness into their applications. Most of these tools are used to
implement front-end state management because that mechanism is easiest to execute and offers the tightest
integration with the application's user base. Front-end state control is also ideal for state management when the
Most tools work by adding a state object to something like JavaScript. This object and its methods are then
used to manage state and prevent loss of state under unusual conditions, including contamination by code or
changes in client-server relationships. Libraries like React focus almost entirely on the user interface. Other
libraries, like Redux or Cerebral, provide an integrated form of state management used throughout the
workflow. Flutter is an SDK that can be used a bit more broadly, in both front-end and back-end state
management applications.
Clicking on a component.
Submitting a form.
Loading images.
Synthetic React Events
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
void persist()
DOMEventTarget target
number timeStamp
string type
Since synthetic events use a lot of resources, they are usually reused and
all its properties will be nullified after invoking the event callback to
optimize their performance in the browser. SyntheticEvent has the same
interface as the native event. And as the synthetic events are authorized
by the document node, native events are triggered first followed by the
synthetic events.
Adding an Event
As we have already seen, React has the same events as HTML: click,
change, mouseover etc. However, the React events are defined with a
camelCase and the reaction is written inside the curly braces instead.
The syntax of adding an event differs in a functional component and
class component.
onClick = {this.action_to_be_performed}
Handling an Event
Let us now learn how to handle these events in a React application with
the help of the following step-by-step process.
log() {
console.log("Event is fired");
log = () => {
console.log("Event is fired");
Arrow Method
Bind Method
Arrow Method
If you want to know the target of the event, then add an argument e in
the handler method. React will send the event target details to the
handler method.
log(e) {
console.log("Event is fired");
console.log(e.target);
console.log("Event is fired");
console.log(e.target);
If you want to send extra details during an event, then add the extra
details as initial argument and then add argument (e) for event target.
log(extra, e) {
console.log("Event is fired");
console.log(e.target);
console.log(extra);
console.log(this);
console.log("Event is fired");
console.log(e.target);
console.log(extra);
console.log(this);
Bind Method
We can also bind the event handler method in the constructor of the
component. This will ensure the availability of this in the event handler
method.
constructor(props) {
super(props);
this.logContent = this.logContent.bind(this);
Set the event handler method for the specific event as specified below −
To set extra arguments, bind the event handler method and then pass the
extra information as second argument.
A constructor is a method that is called automatically when we created an object from that class. It can manage initial
initialization tasks such as defaulting certain object properties or sanity testing the arguments passed in. Simply
placed, the constructor is a method that helps in the creation of objects.
The constructor is no different in React. This can connect event handlers to the component and/or initialize the
component’s local state. Before the component is mounted, the constructor() function is shot, and, like most things in
React, it has a few rules that you can follow when using them.
Step 1: Call super(props) before using this.props
Due to the nature of the constructor, this.props object is not accessible straight out of the gate,
which can lead to errors. An error will be thrown by this constructor:
constructor() {
console.log(this.props);
Instead, we transfer the value of a prop to the super() function from the
constructor():
constructor(props) {
super(props);
console.log(this.props);
When you call the super() function, the parent class constructor is
called, which is in the case of a React is React.Component.
constructor(props) {
super(props);
this.state = {
name 'kapil',
age: 22,
};
The only place you can assign the local state directly like that is the
constructor. You should depend on setState() somewhere else inside our
component instead.
You should try to avoid setting values from the properties when setting
the initial component state in the constructor. We can do the following:
constructor(props) {
super(props);
this.state = {
name: props.name,
};
constructor(props) {
super(props);
this.state = {
};
this.onClick = this.onClick.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
// Rest Code
cd foldername
App.js
constructor(props) {
super(props);
// Creating state
this.state = {
this.handleEvent = this.handleEvent.bind(this);
handleEvent() {
console.log(this.props);
}
render() {
return (
<div >
<br></br> <br></br>
</div>
);
Step to Run Application: Run the application from the root directory of
the project, using the following command
npm start
Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate during its three main
phases.
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
The render() method is required and will always be called, the others are optional and will be called if
you define them.
constructor
The constructor() method is called before anything else, when the component is initiated, and it is the
natural place to set up the initial state and other initial values.
The constructor() method is called with the props, as arguments, and you should always start by
calling the super(props) before anything else, this will initiate the parent's constructor method and
allows the component to inherit methods from its parent ( React.Component).
constructor(props) {
super(props);
render() {
return (
);
The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM.
This is the natural place to set the state object based on the initial props.
It takes state as an argument, and returns an object with changes to the state.
The example below starts with the favorite color being "red", but
the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:
Example:
constructor(props) {
super(props);
render() {
return (
);
Run Example »
render
The render() method is required, and is the method that actually outputs the HTML to the DOM.
Example:
render() {
return (
);
Run Example »
componentDidMount
This is where you run statements that requires that the component is already placed in the DOM.
Example:
At first my favorite color is red, but give me a second, and it is yellow instead:
constructor(props) {
super(props);
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
render() {
return (
);
Run Example »
Updating
The next phase in the lifecycle is when a component is updated.
React Forms
Adding Forms in React
return (
<form>
</label>
</form>
root.render(<MyForm />);
This will work as normal, the form will submit and the page will
refresh.
We want to prevent this default behavior and let React control the form.
Handling Forms
Handling forms is about how you handle the data when it changes value
or gets submitted.
We can use the useState Hook to keep track of each inputs value and
provide a "single source of truth" for the entire application.
Example:
function MyForm() {
return (
<form>
<input
type="text"
value={name}
</label>
</form>
root.render(<MyForm />);
Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute for the <form>:
Example:
function MyForm() {
event.preventDefault();
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
/>
</label>
</form>
root.render(<MyForm />);
Run Example »
To update the state, use square brackets [bracket notation] around the property name.
Example:
Write a form with two input fields:
function MyForm() {
event.preventDefault();
alert(inputs);
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
</form>
)
}
root.render(<MyForm />);
Select
A drop down list, or a select box, in React is also a bit different from HTML.
in HTML, the selected value in the drop down list was defined with the selected attribute:
HTML:
<select>
<option value="Ford">Ford</option>
<option value="Fiat">Fiat</option>
</select>
To create a controlled component, you need to use the value prop to set the value
of form elements and the onChange event to handle changes made to the value.
The value prop sets the initial value of a form element, while the onChange event is
triggered whenever the value of a form element changes. Inside
the onChange event, you need to update the state with the new value using a state
update function
setInputValue(event.target.value);
};
return (
<form>
<label>Input Value:
<input type="text" value={inputValue}
onChange={handleChange} />
</label>
</div>
)};
In this example:
The useState hook defines a state variable (inputValue) and a state update
function (setInputValue).
The value prop sets the initial value of the input element to the value
of inputValue.
Also, the onChange event handles changes made to the input value.
The handleChange function updates the inputValue state with the new value of the
input element, and the updated value is immediately reflected in the state
setInputValue(event.target.value);
};
return (
<form>
<label>Input Value:
<input type="text" value={inputValue}
onChange={handleChange} />
</label>
</div>
)};
In this example:
The useState hook defines a state variable (inputValue) and a state update
function (setInputValue).
The value prop sets the initial value of the input element to the value
of inputValue.
Also, the onChange event handles changes made to the input value.
The handleChange function updates the inputValue state with the new value of the
input element, and the updated value is immediately reflected in the state
For instance, let's say you have a form that consists of a text input field, a select
box, and a checkbox. In a controlled component, you would create a state for
each form element and write event handlers to update the state whenever the
user interacts with any of the form elements.
To get the value of an uncontrolled form element, you can use a feature called
"ref". "Refs" provide a way to access the current value of DOM elements. You can
create a "ref" using the useRef hook, then attach it to the form element you want to
access. This allows you to retrieve the current value of an element at any time,
without needing to manage its state in your React component.
Here's an example of an uncontrolled component:
function handleSubmit(event) {
event.preventDefault();
console.log("Input value:", inputRef.current.value);
console.log("Select value:", selectRef.current.value);
console.log("Checkbox value:", checkboxRef.current.checked);
}
return (
<form onSubmit={handleSubmit}>
<label>
<p>Name:</p>
</label>
<label>
<p>Favorite color:</p>
<select ref={selectRef}>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</label>
<label>
</label>
<button type="submit">Submit</button>
</form>
);
Unit:4
ReactJS - Http client Programming, React Lists, The map() function, React Keys, React Refs, React
Fragments, React Router, ReactCSS, React Animation, React Date picker, DoM in React.
Before we dive into React, let’s set up an Expense REST API server using the
Express framework. This server will serve as our data source.
npm init
Install Dependencies:
npm start
Now, let’s build a React application that interacts with our Expense REST API
server using the fetch() API.
1. Create a React Application:
2. Set up a new React app (e.g., react-http-app) and establish the necessary
folder structure.
7. Fetching Data:
9. Displaying Data:
With this setup, you’ve not only grasped HTTP client programming in React
but also empowered your application to efficiently communicate with the
server.
React Lists
In React, you will render lists with some type of loop.
function Car(props) {
}
function Garage() {
return (
<>
<ul>
</ul>
</>
);
root.render(<Garage />);
Run Example »
Example:
Let's refactor our previous example to include keys:
function Car(props) {
}
function Garage() {
const cars = [
];
return (
<>
<ul>
</ul>
</>
);
root.render(<Garage />);
React Keys are useful when working with dynamically created
components or when editing a list by the user. Setting the key value
uniquely identifies the component even after modification.
Keys must be specified in the field for elements to have stable IDs. We
recommend choosing the key as a string that uniquely identifies an item
in the list.
Example
});
If there are no stable IDs for rendered items, you can assign the item
index as a key to the lists. It can be shown in the below example.
});
Using Keys
Let’s dynamically create a content item with a unique index (i). The
map function creates three elements from the data array. Since the value
of the key must be unique for each element, we also assign it as a key to
each element created.
To avoid mistakes, you have to keep in mind that keys only make sense
in the context of the surrounding array. So, anything you are returning
from the map() function is recommended to be assigned a key.
App.jsx
constructor() {
super();
this.state = {
data:[
component: 'First...',
id: 1
},
component: 'Second...',
id: 2
},
{
component: 'Third...',
id: 3
render() {
return (
<div>
<div>
</div>
</div>
);
render() {
return (
<div>
<div>{this.props.componentData.component}</div>
<div>{this.props.componentData.id}</div>
</div>
);
}
main.js
ReactDOM.render(<App/>, document.getElementById('app'));
Output
First….
Second….
Third….
Creating Refs
Refs are created using React.createRef() and attached to React elements via
the ref attribute. Refs are commonly assigned to an instance property when a component is
constructed so they can be referenced throughout the component.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
Accessing Refs
When a ref is passed to an element in render, a reference to the node becomes accessible at
the current attribute of the ref.
const node = this.myRef.current;
The value of the ref differs depending on the type of the node:
When the ref attribute is used on an HTML element,
the ref created in the constructor
with React.createRef() receives the underlying DOM
element as its current property.
When the ref attribute is used on a custom class
component, the ref object receives the mounted instance
of the component as its current.
You may not use the ref attribute on function
components because they don’t have instances.
The examples below demonstrate the differences.
Adding a Ref to a DOM Element
This code uses a ref to store a reference to a DOM node:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef(); this.focusTextInput =
this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus(); }
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} /> <input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
React will assign the current property with the DOM element when the component mounts,
and assign it back to null when it unmounts. ref updates happen
before componentDidMount or componentDidUpdate lifecycle methods.
Adding a Ref to a Class Component
If we wanted to wrap the CustomTextInput above to simulate it being clicked immediately
after mounting, we could use a ref to get access to the custom input and call
its focusTextInput method manually:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
componentDidMount() {
this.textInput.current.focusTextInput(); }
render() {
return (
<CustomTextInput ref={this.textInput} /> );
}
}
Note that this only works if CustomTextInput is declared as a class:
class CustomTextInput extends React.Component { // ...
}
Refs and Function Components
By default, you may not use the ref attribute on function components because they
don’t have instances:
function MyFunctionComponent() { return <input />;
}
A common pattern in React is for a component to return multiple elements. Fragments let
you group a list of children without adding extra nodes to the DOM.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
There is also a new short syntax for declaring them.
Motivation
A common pattern is for a component to return a list of children. Take this example React
snippet:
class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}
<Columns /> would need to return multiple <td> elements in order for the rendered HTML to
be valid. If a parent div was used inside the render() of <Columns />, then the resulting
HTML will be invalid.
class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}
results in a <Table /> output of:
<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>
Usage
class Columns extends React.Component {
render() {
return (
<React.Fragment> <td>Hello</td>
<td>World</td>
</React.Fragment> );
}
}
which results in a correct <Table /> output of:
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
Short Syntax
There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:
class Columns extends React.Component {
render() {
return (
<> <td>Hello</td>
<td>World</td>
</> );
}
}
You can use <></> the same way you’d use any other element except that it doesn’t support
keys or attributes.
Keyed Fragments
Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for
this is mapping a collection to an array of fragments — for example, to create a description
list:
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
key is the only attribute that can be passed to Fragment. In the future, we may add support
for additional attributes, such as event handlers.