0% found this document useful (0 votes)
29 views44 pages

Full Stack Web Development

The document provides an overview of React JS, a JavaScript library for building user interfaces, detailing its features, benefits, and applications. It explains the architecture of React applications, the role of components, props, and state, and includes instructions for setting up a React development environment. Additionally, it covers JSX, the Virtual DOM, and the differences between functional and class components in React.

Uploaded by

Harikumar.N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views44 pages

Full Stack Web Development

The document provides an overview of React JS, a JavaScript library for building user interfaces, detailing its features, benefits, and applications. It explains the architecture of React applications, the role of components, props, and state, and includes instructions for setting up a React development environment. Additionally, it covers JSX, the Virtual DOM, and the differences between functional and class components in React.

Uploaded by

Harikumar.N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

MC4201 FULL STACK WEB DEVELOPMENT

UNIT IV ADVANCED CLIENT SIDE PROGRAMMING

React JS: ReactDOM - JSX - Components - Properties – Fetch API - State and Lifecycle - -JS Local storage –
Events - Lifting State Up - Composition and Inheritance

React JS 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.

What is React?

React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library created by Facebook.

React is a tool for building UI components.

React Features

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.

 JSX
 Components
 One-way Data Binding
 Virtual DOM
 Simplicity
 Performance

The salient features of React library are as follows −

 Solid base architecture


 Extensible architecture
 Component based library
 JSX based design architecture
 Declarative UI library
Benefits

 Few benefits of using React library are as follows −


 Easy to learn
 Easy to adept in modern as well as legacy application
 Faster way to code a functionality
 Availability of large number of ready-made component
 Large and active community

Applications

 Few popular websites powered by React library are listed below −


 Facebook, popular social media application
 Instagram, popular photo sharing application
 Netflix, popular media streaming application
 Code Academy, popular online training application
 Reddit, popular content sharing application

Architecture of the React Application:


By analyzing the application, we can visualize the workflow of the React application as shown in the below diagram.

React app calls ReactDOM.render method by passing the user interface created using React component
(coded in either JSX or React element format) and the container to render the user interface.
ReactDOM.render processes the JSX or React element and emits Virtual DOM.
Virtual DOM will be merged and rendered into the container.
React 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.

 React app starts with a single root component.


 Root component is build using one or more component.
 Each component can be nested with other component to any level.
 Composition is one of the core concepts of React library. So, each component is build by
composing smaller components instead of inheriting one component from another component.
 Most of the components are user interface components.
 React app can include third party component for specific purpose such as routing, animation, state
management, etc.
React Environment Setup:

Requirements

The Create React App is maintained by Facebook and can works on any platform, for example,
macOS, Windows, Linux, etc. To create a React Project using create-react-app, you need to have
installed the following things in your system.

1. Node version >= 8.10


2. NPM version >= 5.6

Let us check the current version of Node and NPM in the system

Run the following command to check the Node version in the command prompt.

How to install ReactJS

 Here you will learn how to set up environment for successful React development.

 Notice that there are several steps involved but this will help you to speed up progress process later.

 We will need NodeJS so if you don't have it installed, check the link from the below.

Step 1 - Download Node.js Installer for Windows

 Go to the site https://nodejs.org/en/download/ and download the necessary binary files.


Step 2 - Double click on the downloaded .msi file to start the installation.

Step 3 - Select the default components to be installed. Accept the default components and click on the Next button.
Step 4 - In the next screen, click the “Next” button to continue with the installation

Step 4 - Click the Finish button to complete the installation.


Step 5 - Open a terminal(Windows Command Prompt or PowerShell)
Step 6 - We will need some of the npm plugins so let's first install npm by running the following code in command

prompt window.
Step 7 - Creating the app in the “local user” folder.

Step 8 - In order to install your app, first go to your workspace (desktop or a folder) and run the following command: npx

create-react-app my-app
Step 8 - After the folder is created we need to open it and see the following files.

Step 9 - After the installation is completed, change to the directory where your app was installed and finally run npm start to see

your app live on localhost:


Step 10 - It will show you the port we need to open in browser, in our case http://localhost:3000/.

Step 10 - If you see something like this in your browser, you are ready to work with React.
What is JSX in ReactJS ?

 JSX denotes for JavaScript XML. It allows us to write HTML in React.

 It makes it easier to write and add HTML in React.

 JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX

makes React a lot more elegant. Just like XML, JSX tags have a tag name, attributes, and children.

Coding JSX

 It allows us to write HTML elements in JavaScript and place them in the DOM without

any appendChild() and/or createElement() methods.

 It converts HTML tags into react elements.

 To use JSX is not compulsory, but JSX makes it easier to write React applications.

 In this example, JSX allows us to write HTML directly within the JavaScript code. JSX is an extension of the

JavaScript language and is translated into regular JavaScript at runtime.

Expressions in JSX

In JSX you can use expressions inside curly braces { }.

The expression can be a React property, or variable, or some other valid JavaScript expression. It will execute the expression

and return the result.

import React, {useState} from "react";

import ReactDOM from "react-dom";

import './index.css';

const element = <h1> React is {5 + 5} times better with React JSX</h1>;

ReactDOM.render(element, document.getElementById('root'));

Output

React is 10 times better with React JSX


Attribute class = className

 The class attribute is a much-used attribute in HTML, but meanwhile JSX is extracted as JavaScript, and the class

keyword is a reserved word in JavaScript, you are not permitted to use it in JSX.

 You can use attribute className instead.

 JSX resolved this by using className in its place. When JSX is rendered, it interprets className attributes

into class attributes.

Example:

import React, {useState} from "react";

import ReactDOM from "react-dom";

import './index.css';

const element = <h1 className="myclass">Hello Wikitechy</h1>;

ReactDOM.render(element, document.getElementById('root'));

Output

Hello Wikitechy
What is ReactDOM?

ReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to
enable an efficient way of managing DOM elements of the web page. ReactDOM provides the developers with an
API containing the following methods and a few more.

DOM Vs Virtual DOM

What is Real/Browser DOM ?

 DOM stands for "Document Object Model". It denotes the entire UI of the web application as a tree data structure.

 It is a basic representation of the HTML elements of the web application.

 Whenever there is a change in the state of application UI, the DOM gets updated and represents that change.

 With every change, the DOM gets manipulated and re-rendered to update the application UI, which affects the

performance and makes it slower.

 Hence, with more UI components and complex structure of the DOM, the DOM updates will be more costly as with

every change it needs to be re-rendered.

 DOM in HTML Javascript



What is React Virtual DOM ?

 To make the performance of the Real DOM quicker and better, the idea of Virtual DOM shows up. The Virtual DOM

is only the virtual picture of the DOM.

 But the difference is, each time with each change , the virtual DOM gets reorganized instead of the real DOM

 Like, real DOM , virtual DOM is also denoted as a tree structure. Every element is a node in this tree.

 When a new item is added to the application UI, a node is added to the tree also.

 If the state of any of these components changes, another virtual DOM tree is created.

 The virtual DOM figures the most ideal way or we can say the small procedure on the real DOM to make changes to

the real DOM.

 Hence, it makes efficient and better performance by reducing the cost and operations of re-rendering the whole real

DOM.
Now that we have the basic understanding of Real and Virtual DOM, let's focus on how React works using the Virtual DOM.

 In React, each UI is an different component and each component has its individual state.

 React follows the visible pattern and detects the changes of the states.

 Whenever a change is made in the state of any component, React updates the virtual DOM tree but does not change the

real DOM tree.

 After updating, react compares the recent version of the virtual DOM with the earlier version.

 React knows which objects are altered in the virtual DOM, based on that it only changes those objects in the Real

DOM, making minimum working operations.

 This process is noted as "diffing". A picture below will clear the concept more.

 This process is noted as "diffing". A picture below will clear the concept more.
 Here the red circles are the nodes that has been changed. That means, the state of these components is changed. React

computes the difference of the previous and current version of the Virtual DOM tree and the whole parent sub-tree gets

re-rendered to show the changed UI.

 Then the updated tree is batch updated (This means that updates to the real DOM are sent in groups, instead of sending

updates for every single change in state.) to the Real DOM.

What is Props in ReactJS ?

 Props are half of what make React components special.

 State is only seen on the inside of component definitions where as Props are defined when components are created by

either JSX or by pure JavaScript.

 The main difference between state and props is that props are immutable.

 Props are passed to components through HTML attributes. props stands for properties.

React Props

 React Props are like function arguments in JavaScript and attributes in HTML.
 To send props into a component, use the same syntax as HTML attributes:

Sample Code

import React, {useState} from "react";

import ReactDOM from "react-dom";

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

function Wikitechy(props) {

return <h2>Welcome to { props.brand }!</h2>;

const element = <Wikitechy brand="Wikitechy Tutorial" />

ReactDOM.render(element, document.getElementById('root'));

Output

Welcome to Wikitechy Tutorial!


React Components:

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but
work in isolation and return HTML.

React component is the building block of a React application. Let us learn how to create a new React component and
the features of React components in this chapter.
A React component represents a small chunk of user interface in a webpage. The primary job of a React component
is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it
manages the events belongs to its user interface. To summarize, React component provides below functionalities .
 Initial rendering of the user interface.
 Management and handling of events.
 Updating the user interface whenever the internal state is changed.
Every React component have their own structure, methods as well as APIs. They can be reusable as per your need.
For better understanding, consider the entire UI as a tree. Here, the root is the starting component, and each of the
other pieces becomes branches, which are further divided into sub-branches.

React component accomplish these feature using three concepts −


 Properties − Enables the component to receive input.
 Events − Enable the component to manage DOM events and end-user interaction.
 State − Enable the component to stay stateful. Stateful component updates its UI with respect to its state.

In ReactJS, we have mainly two types of components. They are

1. Functional Components
2. Class Components

Functional Components
In React, function components are a way to write components that only contain a render method and
don't have their own state. They are simply JavaScript functions that may or may not receive data as
parameters. We can create a function that takes props(properties) as input and returns what should be
rendered. A valid functional component can be shown in the below example.

1. unction WelcomeMessage(props) {
2. return <h1>Welcome to the , {props.name}</h1>;
3. }
The functional component is also known as a stateless component because they do not hold or
manage state. It can be explained in the below example.

Example

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<First/>
<Second/>
</div>
);
}
}
class First extends React.Component {
render() {
return (
<div>
<h1>JavaTpoint</h1>
</div>
);
}
}
class Second extends React.Component {
render() {
return (
<div>
<h2>www.javatpoint.com</h2>
<p>This websites contains the great CS tutorial.</p>
</div>
);
}
}
export default App;

Output:

Class Components
Class components are more complex than functional components. It requires you to extend from
React. Component and create a render function which returns a React element. You can pass data
from one class to other class components. You can create a class by defining a class that extends
Component and has a render function. Valid class component is shown in the below example.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"name":"Abhishek"
},
{
"name":"Saharsh"
},
{
"name":"Ajay"
}
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}

class List extends React.Component {


render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

Output:

State in Reactjs ?
What is State in Reactjs ?

 State is the place where the data comes from.

 You should try to create your state as simple as possible and minimize number of stateful components.

 For example, ten components that want data from the state, you should create one container component that will

keep the state for all of them.

 Every component has a state object and a props object.

state is set using the setStatemethod.

Calling setState triggers UI updates and is the bread and butter of React's interactivity.

If we want to set an initial state before any interaction occurs we can use the getInitialState method.

reactjs states - States in react js:

 Every component has a State object.

 Can be set by using setState.

 setState triggers UI updates and to get the initial state before the setState : getInitialState.getDefaultProps

 setState triggers UI updates and to get the initial state before the setState :
getInitialState.getDefaultProps
 Reactjs maintained the state – getIntialState, setState, getDefaultProps.

 In the above example we are getting the count variable to 5 and accessing it by {this.state.count}
Article tag : react , react native , react js tutorial , create react app , react tutorial , learn react

Example
var MyComponent = React.createClass({
getInitialState: function(){
return {
count: 5
}
},
render: function(){
return (
<h1>{this.state.count}</h1>
)
}
});
Using Props

 Below code shows how to create stateful component using EcmaScript2016 syntax.

Article tag : react , react native , react js tutorial , create react app , react tutorial , learn react

App.jsx
import React from 'react';

class App extends React.Component {


constructor(props) {
super(props);

this.state = {
header: "Header from state...",
"content": "Content from state..."
}
}

render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}

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
React Component Life-Cycle

Lifecycle Methods

 The component Life cycle has different Phases:

o Mounting

o Updating

o Unmounting
ReactJS, every component creation process involves various lifecycle methods. These lifecycle
methods are termed as component's lifecycle. These lifecycle methods are not very complicated and
called at various points during a component's life. The lifecycle of the component is divided into four
phases. They are:

1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase

Each phase contains some lifecycle methods that are specific to the particular phase. Let us discuss
each of these phases one by one.

1. Initial Phase
It is the birth phase of the lifecycle of a ReactJS component. Here, the component starts its journey on
a way to the DOM. In this phase, a component contains the default Props and initial State. These
default properties are done in the constructor of a component. The initial phase only occurs once and
consists of the following methods.

o getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the creation of the
component or any props from the parent is passed into it.
o getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of the
component.

2. Mounting Phase
In this phase, the instance of a component is created and inserted into the DOM. It consists of the
following methods
o componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In the case,
when you call setState() inside this method, the component will not re-render.
o componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now,
you can do any DOM querying operations.
o 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.

3. Updating Phase
It is the next phase of the lifecycle of a react component. Here, we get new Props and change State.
This phase also allows to handle user interaction and provide communication with the components
hierarchy. The main aim of this phase is to ensure that the component is displaying the latest version
of itself. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of
the following methods.

o componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the state in
response to prop changes, you should compare this.props and nextProps to perform state
transition by using this.setState() method.
o shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows you to
control the component's behavior of updating itself. If this method returns true, the component
will update. Otherwise, the component will skip the updating.
o componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't change the
component state by invoking this.setState() method. It will not be called,
if shouldComponentUpdate() returns false.
o render()
It is invoked to examine this.props and this.state and return one of the following types:
React elements, Arrays and fragments, Booleans or null, String and Number. If
shouldComponentUpdate() returns false, the code inside render() will be invoked again to
ensure that the component displays itself properly.
o componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method, you can put
any code inside this which you want to execute once the updating occurs. This method is not
invoked for the initial render.

4. Unmounting Phase
It is the final phase of the react component lifecycle. It is called when a component instance
is destroyed and unmounted from the DOM. This phase contains only one method and is given
below.

o 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: "JavaTpoint"};
this.changeState = this.changeState.bind(this)
}
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!!- Its a great reactjs tutorial."});
}
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!')
}
}
export default App;
Output:

When you click on the Click Here Button, you get the updated result which is shown in the below
screen.
LocalStorage in ReactJS:
LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data
is saved across browser sessions and the data stored has no expiration time.

Syntax
// To store data
localStorage.setItem('Name', 'Rahul');

// To retrieve data
localStorage.getItem('Name');

// To clear a specific item


localStorage.removeItem('Name');

// To clear the whole data stored in localStorage


localStorage.clear();

Set, retrieve and remove data in localStorage


In this example, we will build a React application which takes the username and password from the user and stores it
as an item in the localStorage of the user’s computer.

Example
App.jsx
import React, { useState } from 'react';

const App = () => {

const [name, setName] = useState('');


const [pwd, setPwd] = useState('');

const handle = () => {


localStorage.setItem('Name', name);
localStorage.setItem('Password', pwd);
};
const remove = () => {
localStorage.removeItem('Name');
localStorage.removeItem('Password');
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="Password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>

<button onClick={handle}>Done</button>
</div>
{localStorage.getItem('Name') && (
<div>
Name: <p>{localStorage.getItem('Name')}</p>
</div>
)}
{localStorage.getItem('Password') && (
<div>
Password: <p>{localStorage.getItem('Password')}</p>
</div>
)}
<div>
<button onClick={remove}>Remove</button>
</div>
</div>
);
};
export default App;

Output
This will produce the following result.
Lifting State up in ReactJS
Lifting up the State: As we know, every component in React has its own state. Because of this sometimes data can be
redundant and inconsistent. So, by Lifting up the state we make the state of the parent component as a single source
of truth and pass the data of the parent in its children.
Time to use Lift up the State: If the data in “parent and children components” or in “cousin components” is Not in Sync.
Example 1: If we have 2 components in our App. A -> B where, A is parent of B. keeping the same data in both
Component A and B might cause inconsistency of data.
Example 2: If we have 3 components in our App.
A
/\
B C
Where A is the parent of B and C. In this case, If there is some Data only in component B but, component C also
wants that data. We know Component C cannot access the data because a component can talk only to its parent or
child (Not cousins).
Problem: Let’s Implement this with a simple but general example. We are considering the second example.
Complete File Structure:

Approach: To solve this, we will Lift the state of component B and component C to component A. Make A.js as our
Main Parent by changing the path of App in the index.js file
Before:
import App from './App';
After:
import App from './A';
Filename- A.js
import React,{ Component } from 'react';

class B extends Component {


constructor(props) {
super(props);
this.handleTextChange = this.handleTextChange.bind(this);
}

handleTextChange(e){
this.props.handleTextChange(e.target.value);
}

render() {
return (
<input value={this.props.text}
onChange={this.handleTextChange} />
);
}
}

export default B;
React Events:

An event is an action that could be triggered as a result of the user action or system generated event. For example, a
mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.
React has its own event handling system which is very similar to handling events on DOM elements. The react event
handling system is known as Synthetic Events. The synthetic event is a cross-browser wrapper of the browser's
native event.

Handling events with react have some syntactic differences from handling events on DOM. These are:
React events are named as camelCase instead of lowercase.
With JSX, a function is passed as the event handler instead of a string. For example
Adding Events
React events are written in camelCase syntax:
onClick instead of onclick.
React event handlers are written inside curly braces:
onClick={shoot} instead of onClick="shoot()".
React:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>

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() {
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:
When you execute the above code, you will get the following output.

After entering the name in the textbox, you will get the output as like below screen.

Component API in Reactjs ?

What is Component API in Reactjs ?


In React component API has three methods:
setState(),
forceUpdate and
ReactDOM.findDOMNode().
In new ES6 classes we have to manually bind this.
You will see in examples below that we are using this.method.bind(this).
 Instead of a React Component are created internally in React when rendering.These instances are reused in subsequent

renders,and can be accessed in your component methods as this.

learn reactjs tutorial -

reactjs component API set state

- reactjs example - react tutorial - reactjs - react

Set State

 setState() method is used for updating the state of the component.

 This method will not replace the state but only add changes to original state

Example:
import React from 'react';

class App extends React.Component {

constructor() {

super();

this.state = {

data: []

}
this.setStateHandler = this.setStateHandler.bind(this);

};

setStateHandler() {

var item = "setState..."

var myArray = this.state.data;

myArray.push(item)

this.setState({data: myArray})

};

render() {

return (

<div>

<button onClick = {this.setStateHandler}>SET STATE</button>

<h4>State Array: {this.state.data}</h4>

</div>

);

export default App;

Output:

Force Update

 Sometimes you want to update the component manually.

 You can achieve this by using forceUpdate() method.


import React from 'react';

class App extends React.Component {


constructor() {
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};

forceUpdateHandler() {
this.forceUpdate();
};

render() {
return (
<div>
<button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;

 We are setting random number that will be updated every time the button is clicked.

Output

Find Dom Node

 For DOM manipulation, we can use ReactDOM.findDOMNode() method.

 First we need to import react-dom.

Output
Composition And Inheritance In React.Js:

Composition and inheritance are the approaches to use multiple components together in React.js . This helps in code reuse. React
recommend using composition instead of inheritance as much as possible and inheritance should be used in very specific cases
only.
Example to understand it −
Let’s say we have a component to input username.

Inheritance
class UserNameForm extends React.Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
ReactDOM.render(
< UserNameForm />,
document.getElementById('root'));
This sis simple to just input the name. We will have two more components to create and update the username field.
With the use of inheritance we will do it like −
class UserNameForm extends React.Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
class CreateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Create</button>
</div>
)
}
}
class UpdateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Update</button>
</div>
)
}
}
ReactDOM.render(
(<div>
< CreateUserName />
< UpdateUserName />
</div>), document.getElementById('root')
);
We extended the UserNameForm component and extracted its method in child component using super.render();
Composition
class UserNameForm extends React.Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
class CreateUserName extends React.Component {
render() {
return (
<div>
< UserNameForm />
<button>Create</button>
</div>
)
}
}
class UpdateUserName extends React.Component {
render() {
return (
<div>
< UserNameForm />
<button>Update</button>
</div>
)
}
}
ReactDOM.render(
(<div>
<CreateUserName />
<UpdateUserName />
</div>), document.getElementById('root')
);

You might also like