Unit IV
Unit IV
React: Introduction
ReactJS is a declarative, efficient and flexible JavaScript library for building reusable
UI components.
It is an open-source, component-based front end library responsible only for the
view layer of the application.
It was created by Jordan Walke, who was a software engineer at Facebook.
It was initially developed and maintained by Facebook and was later used in its
products like WhatsApp & Instagram.
Facebook developed ReactJS in 2011 in its newsfeed section, but it was released
to the public in the month of May 2013.
Recently, most of the websites are built using MVC (Model View Controller)
architecture.
In MVC architecture, React is the 'V' which stands for view in web and mobile
apps., whereas the architecture is provided by the Redux or Flux.
A ReactJS application is made up of multiple components, each component
responsible for outputting a small, reusable piece of HTML code.
The components are the heart of all React applications. These Components can be
nested with other components to allow complex applications to be built of simple
building blocks.
ReactJS uses virtual DOM based mechanism to fill data in HTML DOM.
The virtual DOM works fast as it only changes individual DOM elements instead
of reloading complete DOM every time.
To create React app, we write React components that correspond to various
elements.
We organize these components inside higher level components which define the
application structure.
1|Page
Reasons to use React JS
Today, many JavaScript frameworks are available in the market (angular, node),
but still, React came into the market and gained popularity amongst them.
The previous frameworks follow the traditional data flow structure, which uses the
DOM. It is an object which is created by the browser each time a web page is
loaded.
It dynamically adds or removes the data at the back end and when any
modifications were done, then each time a new DOM is created for the same page.
This repeated creation of DOM makes unnecessary memory wastage and reduces
the performance of the application. A new technology ReactJS framework was
invented which remove this drawback.
ReactJS allows you to divide your entire application into various components.
ReactJS still used the same traditional data flow, but it is not directly operating on
the browser's DOM immediately; instead, it operates on a virtual DOM.
It means rather than manipulating the document in a browser after changes to our
data, it resolves changes on a DOM built and run entirely in memory.
After the virtual DOM has been updated, React determines what changes made to
the actual browser's DOM.
The React Virtual DOM exists entirely in memory and is a representation of the
web browser's DOM.
Features of React JS
2|Page
JSX (JavaScript Syntax Extension): This markup syntax describes how the
application's user interface will appear. Developers use it to create React
components, making the syntax similar to HTML. JSX is one of the best features
of React as it makes it extremely simple for developers to write the building
blocks.
Virtual DOM: A virtual DOM object is a DOM object representation that creates
a virtual copy of the original DOM object. The entire UI is re-rendered in the
virtual DOM representation when the web application is changed. The old DOM
representation is then compared to the new DOM representation. Following that,
the actual DOM will only update the changed elements. This React feature
facilitates and speeds up the application development process.
One-way data binding: React uses a unidirectional data flow, forcing developers
to edit components via the callback feature rather than directly editing them. The
Flux JS application's architecture component aids in the unidirectional flow of
data. This increases the application's flexibility, which leads to increased
efficiency.
Performance: React uses virtual DOM and updates only the modified parts. So,
this makes the DOM to run faster. DOM executes in memory so we can create
separate components which makes the DOM run faster.
Extensions: It supports mobile app development and provides server-side
rendering. It is extended with Flux, Redux, React Native, etc. which helps us to
create full-fledged UI applications.
Simplicity: React.js is a component-based which makes the code reusable and
React.js uses JSX which is a combination of HTML and JavaScript. This makes
code easy to understand and easy to debug and has less code. Few popular
websites powered by React library are,
Facebook: popular social media application
Instagram: popular photo sharing application
3|Page
Netflix: popular media streaming application
Code Academy: popular online training application
Reddit: popular content sharing application
Installation of React JS
Step 1: Install Nodejs
Node.js provides a runtime environment to execute JavaScript code from outside a
browser. NPM, the Node package manager is used for managing and sharing the
packages for either React or Angular. NPM will be installed along with Nodejs.
Node.js can be downloaded and installed from the official NodeJs website
https://nodejs.org. Once the Installation of Node is complete. Open Node.Js
Command Prompt and we can check the version as well.
node -v npm -v
These commands will display the version numbers for Node.js and npm,
respectively.
Step 2: Install Create-React-App
The next step is to install a tool called create-react-app using NPM. It is a
command-line tool that simplifies the process of setting up a new React project
with a recommended project structure and configuration. To install Create React
App globally, open a command prompt and run the following command:
npm install -g create-react-app
This command installs Create React App on your system, making it available to
use in any directory.
Create React APP
create-react-app --version
This command tells the installed version of react app.
Step 3: Now Create a new folder where you want to make your react app using the
following command,
mkdir folder_name
4|Page
This command will create a new directory.
Step 4: Create a New React Project
Now that you have Create React App installed, you can use it to create a new
React project. To do this, open a command prompt, go to the directory where you
want the project to live, and run the following command:
create-react-app my-app
The command Create React App will create a new directory with the specified
name and generate a new React project with a recommended project structure and
configuration.
Step 5: Go To the Project Directory and Start the Development Server
Once the project is created, head over to the project directory by running the
following command in the command prompt:
cd my-app
npm start
This command launches the development server, which watches for changes to
your project files and automatically reloads the browser when changes are
detected.
A new browser window is opened with React application running
at http://localhost:3000/ as,
5|Page
Components of React JS
Introduction
For the development of a single-page application, the developers used to write
hundreds of lines of code.
Making changes and updates to these applications was quite tricky because they
adhere to the conventional DOM structure.
The entire application was manually searched and updated if a mistake was
discovered.
The react component-based methodology was developed to address a problem.
This method breaks down the entire application into a handful of manageable,
logical groups of code or components.
Definition:
A Component is one of the fundamental elements of a React application.
Construction of UIs becomes substantially simpler as a result.
The final user interface of the application will be made up of a parent component
that unifies all the child components, even if they all share the same space.
Along with rendering the UI, components in react also control the events related to
that UI.
To sum up, the React component offers the following features.
6|Page
Rendering of the user interface's initial stage.
Event handling and management.
Anytime there is a change to the internal state, update the user interface.
React components use three concepts to implement these features.
Properties: Allows the component to accept input.
Events: Make the component capable of controlling DOM events and user
interaction.
State: Allows the component to continue being stateful. With regard to its state, a
stateful component modifies its user interface.
Types of Components in React:
Two types of components exist in the React library. The types are divided into
groups according to how they are produced:
Functional components in react are used to create components in React that do not
have their own state and only return JSX.
They are basically JavaScript functions that might or might not include parameters
that contain data.
We can write a function that accepts the props(properties) argument and outputs
the displayed result.
Example:
function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>; }
Since the functional component does not store or handle the state, it is also
referred to as a stateless component.
React does, however, provide a hook called useState() that enables function
components to keep track of their state.
There is no life cycle for a functional component.
For the functional component to access the component's various stages, React
offers a hook called useEffect().
7|Page
Able to group several functional components together under a single functional
component.
Class component:
In comparison to functional components, class components are more complex.
To develop class-based components in React, we can use JavaScript ES6 classes.
To define a React component class, you need to extend React.Component.
You must develop a render method that returns a React element by extending from
React.Component.
Data can be passed between classes and between class components.
Class component: Example
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Due to their ability to contain or manage local state, class components are also
known as stateful components.
The life cycle of a class component is accessible through specific callback APIs,
which also provide access to each life cycle event.
Rendering component:
How ReactDOM.render() method renders elements that were initialized using DOM
tags?
In React, we can either supply the component itself as the first argument to the
ReactDOM.render() method or initialize an element with a user-defined component and
pass this element as the first input to the method.
const element = <div />;
const elementName = <ComponentName />;
8|Page
The ComponentName in the syntax mentioned above refers to the user-defined
component.
Example: Open the project directory's and create index.js file
import React from 'react';
import ReactDOM from 'react-dom';
// This is a functional component
const Welcome=()=>
{
return <h1>Hello World!</h1>
}
ReactDOM.render(<Welcome />, document.getElementById("root") );
State
A state is an object that holds data and information related to a React component.
It can be used to store, manage, and update data within the application, which in
turn allows for dynamic changes to user interfaces.
A state can be used in functional and class components, but it is more commonly
used in class components.
A state represents the component's local state or information. It can only be
accessed or modified inside the component or by the component directly.
Example: if we have five components that need data or information from the
state, then we need to create one container component that will keep the state for
all of them.
To define a state, declare a default set of values for defining the component's
initial state. To do this, add a class constructor which assigns an initial state using
this.state.
The „this.state‟ property can be rendered inside render() method.
When the state object changes, the component re-renders.
9|Page
Creating the state Object: The state object is initialized using constructor
Example 1:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return ( <div> <h1>My Car</h1> </div>); }
}
Example 2:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = { brand: "Ford", model: "Mustang", color: "red", year:
1964 };
}
render() {
return (<div> <h1>My Car</h1> </div> );
}
}
Using the state Object:
Refer the state object anywhere in the component by using the
this.state.propertyname
Example 3:
import React from 'react';
import ReactDOM from 'react-dom/client';
10 | P a g e
constructor(props) {
super(props);
this.state = {brand: "Ford", model: "Mustang", color: "red", year: 1964 };
}
render() {
return ( <div>
<h1>My {this.state.brand}</h1>
<p> It is a {this.state.color} {this.state.model} from {this.state.year}. </p>
</div> );
}}
11 | P a g e
this.state = { brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p> It is a {this.state.color}
{this.state.model}
from {this.state.year}. </p>
<button type ="button“ onClick={this.changeColor}>
Change color </button>
</div>
);
}}
Output:
12 | P a g e
Props
Props stand for “Properties” They are read-only components. It is an object which
stores the value of attributes of a tag and work similar to the HTML attributes.
It provides a way to pass data from one component to other components. It is
similar to function arguments.
Props are passed to the component in the same way as arguments passed in a
function.
Props are immutable so we cannot modify the props from inside the component.
Instead of it, we can add attributes called props.
These attributes are available in the component as this.props and can be used to
render dynamic data in our render method.
Syntax:
// Passing Props
<DemoComponent sampleProp = "HelloProp" />
In the above code snippet, we are passing a prop named sampleProp to the
component named DemoComponent. This prop has the value “HelloProp”.
To access any props inside from the component‟s class to which the props is
passed.
Syntax:
// Accessing props
this.props.propName;
The „this.props‟ is a kind of global object which stores all of a component‟s props.
The propName, that is the names of props are keys of this object.
Example 1:
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
13 | P a g e
}
function Garage() {
return ( <>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" /> </>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Output:
Example 2: Add props to reactDOM.render() function in main.js and use it inside our
component
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return ( <div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>);
}
} export default App;
14 | P a g e
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App headerProp = "Header from props..." contentProp =
"Content from props..."/>, document.getElementById('app'));
export default App;
Output:
Default Props
Also set default property values directly on the component constructor instead of
adding it to the reactDom.render() element.
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div> );
}}
App.defaultProps = {
15 | P a g e
headerProp: "Header from props...",
contentProp:"Content from props..."
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Output:
17 | P a g e
Output:
The difference is i.e. the source of our data, which is now originated from the
state. When we need to update it, just update the state, and all child components will be
updated.
Props Validation
Props are used to passing the read-only attributes to React components.
For the proper functioning of components and to avoid future bugs and glitches it
is necessary that props are passed correctly and also to improve the react
component‟s performance.
React JS has an inbuilt feature for validating props data type to make sure that
values passed through props are valid.
React components have a property called propTypes which is used to setup data
type validation.
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:
class Component extends React.Component {
render() {}
}
18 | P a g e
Component.propTypes = {/* definition goes here*/};
ReactJS props validator contains the following list of validators
PropsType Description
PropTypes.any prop can be of any data type.
PropTypes.bool prop should be a boolean.
PropTypes.number prop should be a number.
PropTypes.string prop should be a string.
PropTypes.func prop should be a function.
PropTypes.array prop should be an array.
PropTypes.object prop should be an object.
PropTypes.symbol prop should be a symbol.
PropTypes.isRequired prop should be provided.
PropTypes.oneOf() props should be one of several types of specified values.
PropTypes.element props must be an element.
PropTypes.instanceOf prop should be an instance of a particular JavaScript class.
Example:
import React from 'react';
import PropTypes from 'prop-types';
function MyComponent(props)
{
return <h1>Hello, {props.name}!</h1>;
}
MyComponent.propTypes = { name: PropTypes.string.isRequired
};
export default MyComponent;
19 | P a g e
State Vs Props
State Props
State changes can be asynchronous. Props are read-only.
20 | P a g e
The implementation of the constructor for a React component, is to call
super(props) method before any other statement.
If super(props) method is not used then, this.props will be undefined in the
constructor and can lead to bugs.
Syntax
Constructor(props){
super(props);
}
In React, constructors are mainly used for two purposes:
It used for initializing the local state of the component by assigning an object to
this.state.
It used for binding event handler methods that occur in the component.
Not to call setState() method directly in the constructor(). If the component needs
to use local state, directly use 'this.state' to assign the initial state in the
constructor.
The constructor only uses this.state to assign initial state, and all other methods
need to use set.state() method.
Example:
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.handleClick = this.handleClick.bind(this);
}
21 | P a g e
handleClick() {
this.setState(prevState => ({ count: prevState.count + 1 }));
}
render() {
return ( <div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
export default App;
Output:
Code Explanation:
MyComponent class has a constructor that initializes the state with a count
property set to 0. It also binds the handleClick method to the instance of the component
using the bind() method. The handleClick method is defined to update the component‟s
state when the button is clicked. It calls the setState() method to update the count
property of the state. In the render() method, the count property of the state is displayed
along with a button that calls the handleClick method when clicked.
22 | P a g e
Component API
ReactJS component is a top-level API. It makes the code completely individual
and reusable in the application. It includes various methods used for,
Creating elements
Transforming elements
Fragments
The three most important methods available in the React component API are,
setState()
forceUpdate()
findDOMNode()
The setState() method:
The setState() method is a primary method which is used to set or update a state of
the component and it also triggers UI updates on calling. It does not replace the state
immediately, but only adds changes to the original state. It is also used to update the user
interface(UI) in response to event handlers and server responses.
Syntax:
this.stateState(object newState, function_callback);
Parameters: function_callback: It is an optional parameter, executed once setState() is
completed and the component is re-rendered.
Example
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello World"
};
23 | P a g e
this.updateSetState = this.updateSetState.bind(this);
}
updateSetState() {
this.setState({ message:"It is a beautiful day."});
}
render() {
return ( <div>
<h1>{this.state.message}</h1>
<button onClick = {this.updateSetState}>SET</button>
</div> );
} }
export default App;
Output:
24 | P a g e
Example
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor() {
super();
this.forceUpdateState = this.forceUpdateState.bind(this);
}
forceUpdateState() {
this.forceUpdate();
};
render() {
return ( <div>
<h1>Random number</h1>
<h3>{Math.random()}</h3>
<button onClick = {this.forceUpdateState}>Update</button>
</div>
);
} }
export default App;
Output:
Setting a random number that will be updated every time the button is clicked.
25 | P a g e
The findDOMNode() method:
It is used for DOM manipulation, to find or access the underlying DOM node.
Syntax:
ReactDOM.findDOMNode (component);
Example
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.findDomNodeHandler = this.findDomNodeHandler.bind(this);
};
findDomNodeHandler() {
var myDiv = document.getElementById('myDiv');
ReactDOM.findDOMNode(myDiv).style.color = 'red'; }
render() {
return (
<div>
<button onClick = {this.findDomNodeHandler}>FIND DOME
NODE</button>
<div id = "myDiv">NODE</div>
</div>
);
}
}
export default App;
26 | P a g e
Output:
27 | P a g e
Initial Phase: This is the phase in which the component is going to initialize by
setting up the state and the props. This is usually done inside the constructor
method. For example,
class Initialize extends React.Component {
constructor(props)
{
//Calling parent class constructor
super(props);
// Set initial state
this.state = { date : new Date(),
clickedStatus: false };
}
Mounting: is the phase of the react lifecycle that comes after the initialization is
completed. Mounting occurs when the component is placed on the DOM container
and the component is rendered on a webpage. The mounting phase has two
methods which are:
compnentWillMount(): This is invoked immediately before a component gets
rendered into the DOM. In this case, when calling setState() inside this
method, the component will not re-render.
componentDidMount(): This is invoked immediately after a component gets
rendered and placed on the DOM. Now, you can perform any DOM querying
operations.
render(): This method is defined in each and every component. It is
responsible for returning a single root HTML node element. If you don't want
to render anything, you can return a null or false value.
Updation: get new Props and change State. This phase also allows handling user
interaction and providing communication with the components hierarchy. The
main aim of this phase is to ensure that the component is displaying the latest
version of itself.
28 | P a g e
componentWillRecieveProps(): It is invoked when a component receives new
props to update the state in response to prop changes.
shouldComponentUpdate(): It is invoked when a component decides any
changes/updation to the DOM. It allows to control the component's behavior of
updating itself. This method returns true, the component will update.
Otherwise, the component will skip the updating.
componentWillUpdate(): It is invoked before the component updating occurs.
Here, you can't change the component state by invoking this.setState() method.
componentDidUpdate(): It is invoked immediately after the component
updating occurs. The code placed inside this method will execute once the
updating occurs. This method is not invoked for the initial render.
render(): It is invoked to examine this.props and this.state and return one of
the following types of React elements like, Arrays, Booleans or null, String
and Number.
Unmounting: It is called when a component instance is destroyed and unmounted
from the DOM. This phase contains only one method and is given below.
componentWillUnmount(): This method is invoked immediately before a
component is destroyed and unmounted permanently. It performs any
necessary cleanup related task such as invalidating timers, event listener,
canceling network requests, or cleaning up DOM elements. If a component
instance is unmounted, you cannot mount it again.
Example:
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {hello: "Mr.Steve Johnson"};
this.changeState = this.changeState.bind(this)
}
29 | P a g e
render() {
return (<div>
<h1>ReactJS component's Lifecycle</h1>
<h3>Hello {this.state.hello}</h3>
<button onClick = {this.changeState}>Click Here!</button>
</div> ); }
componentWillMount() {
console.log('Component Will MOUNT!')
}
componentDidMount() {
console.log('Component Did MOUNT!')
}
changeState(){
this.setState({hello:"All are Welcome!!"});
}
componentWillReceiveProps(newProps) {
console.log('Component Will Recieve Props!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component Will UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Did UPDATE!')
}
componentWillUnmount() {
console.log('Component Will UNMOUNT!')
30 | P a g e
}
} export default App;
Output:
Conditional Rendering
In React, conditional rendering is the process of displaying different content based
on certain conditions or states. It allows to create dynamic user interfaces that can adapt
to changes in data and user interactions. In this process, the developer can use conditional
statements to decide what content should be rendered. There are several reasons to use
conditional rendering in React applications
Improve the User Experience
Improve Performance
Simplified Code
Flexibility
There is more than one way to do conditional rendering in React. They are,
if
31 | P a g e
ternary operator
logical && operator
switch case operator
Conditional Rendering with enums
if: It is the easiest way to have a conditional rendering in React in the render
method. It is restricted to the total block of the component. IF the condition is true,
it will return the element to be rendered.
Example:
function SignUp(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserLogin />;
}
return <GuestLogin />;
}
Logical && operator: This operator is used for checking the condition. If the
condition is true, it will return the element right after &&, and if it is false, React
will ignore and skip it.
Syntax:
{
condition &&
// whatever written after && will be a part of output.
}
Example:
import React from 'react';
import ReactDOM from 'react-dom';
// Example Component
function Example()
{
32 | P a g e
return(<div>
{
(10 > 5) && alert('This alert will be shown!')
}
</div>
);
}
Ternary operator: It is used in cases where two blocks alternate given a certain
condition. This operator makes your if-else statement more concise. It takes three
operands and used as a shortcut for the if statement.
Syntax:
condition ? true : false
If the condition is true, statement1 will be rendered. Otherwise, false will be
rendered.
Example:
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
Welcome {isLoggedIn ? 'Back' : 'Please login first'}.
</div>
);
}
Switch case operator: It is possible to have multiple conditional renderings. In
the switch case, conditional rendering is applied based on a different state. For
example,
function Dashboard(props) {
const { userRole } = props;
switch (userRole) {
33 | P a g e
case 'admin':
return <AdminDashboard />;
case 'user':
return <UserDashboard />;
default:
return <div>Error: Invalid User Role</div>;
}}
Conditional Rendering with enums: An enum is a great way to have a multiple
conditional rendering. It is more readable as compared to switch case operator. It
is used for mapping between different state and also perfect for mapping more
than one condition. For example,
function NotificationMsg({ text, state }) {
return (
<div>
{{ info: <Message text={text} />,
warning: <Message text={text} />,
}[state]}
</div> );
}
Forms in React
Forms are an integral part of any modern web application.
It allows the users to interact with the application as well as gather information
from the users.
Forms can perform many tasks that depend on the nature of your business
requirements and logic such as authentication of the user, adding user, searching,
filtering, booking, ordering, etc.
A form can contain text fields, buttons, checkbox, radio button, etc.
34 | P a g e
Creating Forms
React offers a stateful, reactive approach to build a form.
The component rather than the DOM usually handles the React form.
In React, the form is usually implemented by using controlled components. There
are mainly two types of form input in React.
1. Uncontrolled component
2. Controlled component
Uncontrolled component: The uncontrolled input is similar to the traditional
HTML form inputs. The DOM itself handles the form data. Here, the HTML
elements maintain their own state that will be updated when the input value
changes. To write an uncontrolled component, use a ref to get form values from
the DOM. In other words, there is no need to write an event handler for every state
update. Use a ref to access the input field value of the form from the DOM.
Uncontrolled component Example:
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.updateSubmit = this.updateSubmit.bind(this);
this.input = React.createRef();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName successfully.');
}
render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name: <input type="text" ref={this.input} />
35 | P a g e
</label>
<label>CompanyName: <input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
); }
} export default App;
Output:
After filling the data in the field you will able to get the message while clicking the
submit button.
Controlled component
In HTML, form elements typically maintain their own state and update it
according to the user input. In the controlled component, the input form element is
handled by the component rather than the DOM. Here, the mutable state is kept in the
state property and will be updated only with setState() method. Controlled components
have functions that govern the data passing into them on every onChange event, rather
than grabbing the data only once, for example, when you click a submit button. This data
is then saved to state and updated with setState() method. This makes component have
better control over the form elements and data. A controlled component takes its current
36 | P a g e
value through props and notifies the changes through callbacks like an onChange event.
A parent component "controls" this change by handling the callback and managing its
own state and then passing the new values as props to the controlled component. It is also
called as a "dumb component."
Controlled component Example:
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) { super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label> Name:
<input type="text" value={this.state.value}
onChange={this.handleChange} />
</label> <input type="submit" value="Submit" />
</form>
);
} }
37 | P a g e
export default App;
Output:
After filling the data in the field you will able to get the message while clicking the
submit button.
Events in React
Every web application tends to have user interaction. These interactions are made
through events. An event is a type of action that can be triggered by a user or a system-
generated event, for example, a mouse click, page loading, and other interactions. Just
like DOM events, React has its own event handling system known as SyntheticEvents.
These event handlers will be passed instances of SyntheticEvent. There are some syntax
differences between DOM events and React events:
React events are named in camelCase (like onClick), rather than all lowercase.
The event listener or event handler is a function surrounded by curly brackets, as
opposed to HTML, where the event handler or event listener is a string. For
example, in HTML, we do something like the following:
<button onclick="displayMessage()">
Hello World!
</button>
38 | P a g e
It is slightly different in React:
<button onClick={displayMessage}>
Hello World!
</button>
React cannot return false to prevent the default behavior. We must call
preventDefault event explicitly to prevent the default behavior. For example,
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}> Click_Me </a>
); }
In plain HTML, to prevent the default link behavior of opening a new page. For
example,
<a href="#" onclick="console.log('You had clicked a Link.');
return false"> Click_Me </a>
Example:
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { companyName: „ ‟ };
}
changeText(event) {
this.setState({ companyName: event.target.value });
}
render() {
39 | P a g e
return ( <div>
<h2>Simple Event Example</h2>
<label htmlFor="name">Enter company name: </label>
<input type="text" id="companyName" onChange={this.changeText.bind(this)}/>
<h4>You entered: { this.state.companyName }</h4>
</div> );
}
}
export default App;
Output:
40 | P a g e