MC4201 Unit 4
MC4201 Unit 4
React JS
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.
Today, most of the websites are built using MVC (model view controller) architecture.
In MVC architecture, React is the 'V' which stands for view, whereas the architecture
is provided by the Redux or Flux.
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. For example, we take a form that consists of many elements like
input fields, labels, or buttons. We can write each element of the form as React
components, and then we combine it into a higher-level component, i.e., the form
component itself. The form components would specify the structure of the form along
with elements inside of it.
Today, many JavaScript frameworks are available in the market(like 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
(Document Object Model). DOM 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.
There are two ways to set up an environment for successful ReactJS application. They
are given below.
Create a root folder with the name reactApp on the desktop or where you want. Here,
we create it on the desktop. You can create the folder directly or using the command
given below.
Now, you need to create a package.json file. To create any module, it is required to
generate a package.json file in the project folder. To do this, you need to run the
following command as shown in the below image.
After creating a package.json file, you need to install react and its DOM packages
using the following npm command in the terminal window as shown in the below
image.
You can also use the above command separately which can be shown as below.
If you do not want to install react by using webpack and babel, then you can choose
create-react-app to install react. The 'create-react-app' is a tool maintained by
Facebook itself.
Install React
You can install React using npm package manager by using the below command.
There is no need to worry about the complexity of React installation. The
create-react-app npm package will take care of it.
After the installation of React, you can create a new react project using
create-react-app command. Here, I choose jtp-reactapp name for my project.
1. javatpoint@root:~/>create-react-app jtp-reactapp
NOTE: You can combine the above two steps in a single command using npx.
The npx is a package runner tool that comes with npm 5.2 and above version.
The above command will install the react and create a new project with the name
jtp-reactapp. This app contains the following sub-folders and files by default which
can be shown in the below image.
Now, to get started, open the src folder and make changes in your desired file. By
default, the src folder contain the following files shown in below image.
For example, I will open App.js and make changes in its code which are shown
below.
App.js
After completing the installation process, you can start the server by running the
following command.
1. javatpoint@root:~/Desktop>cd jtp-reactapp
2. javatpoint@root:~/Desktop/jtp-reactapp>npm start
It will show the port number which we need to open in the browser. After we open it,
you will see the following output.
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
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.
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.
Today, ReactJS is the highly used open-source JavaScript Library. It helps in creating
impressive web apps that require minimal effort and coding. The main objective of
ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. There
are important pros and cons of ReactJS given as following:
Advantage of ReactJS
ReactJS is much easier to learn and use. It comes with a good supply of
documentation, tutorials, and training resources. Any developer who comes from a
JavaScript background can easily understand and start creating web apps using React
in a few days. It is the V(view part) in the MVC (Model-View-Controller) model, and
referred to as ?one of the JavaScript frameworks.? It is not fully featured but has the
advantage of open-source JavaScript User Interface(UI) library, which helps to
execute the task in a better manner.
To create a dynamic web application specifically with HTML strings was tricky
because it requires a complex coding, but React JS solved that issue and makes it
easier. It provides less coding and gives more functionality. It makes use of the
JSX(JavaScript Extension), which is a particular syntax letting HTML quotes and
HTML tag syntax to render particular subcomponents. It also supports the building of
machine-readable codes.
3. Reusable Components
4. Performance Enhancement
React JS has also gained popularity due to the presence of a handy set of tools. These
tools make the task of the developers understandable and easier. The React Developer
Tools have been designed as Chrome and Firefox dev extension and allow you to
inspect the React component hierarchies in the virtual DOM. It also allows you to
select particular components and examine and edit their current props and state.
Traditional JavaScript frameworks have an issue in dealing with SEO. The search
engines generally having trouble in reading JavaScript-heavy applications. Many web
developers have often complained about this problem. ReactJS overcomes this
problem that helps developers to be easily navigated on various search engines. It is
because React.js applications can run on the server, and the virtual DOM will be
rendering and returning to the browser as a regular web page.
ReactJS applications are extremely easy to test. It offers a scope where the developer
can test and debug their codes with the help of native tools.
Disadvantage of ReactJS
The high pace of development has an advantage and disadvantage both. In case of
disadvantage, since the environment continually changes so fast, some of the
developers not feeling comfortable to relearn the new ways of doing things regularly.
It may be hard for them to adopt all these changes with all the continuous updates.
They need to be always updated with their skills and learn new ways of doing things.
2. Poor Documentation
It is another cons which are common for constantly updating technologies. React
technologies updating and accelerating so fast that there is no time to make proper
documentation. To overcome this, developers write instructions on their own with the
evolving of new releases and tools in their current projects.
3. View Part
ReactJS Covers only the UI Layers of the app and nothing else. So you still need to
choose some other technologies to get a complete tooling set for development in the
project.
4. JSX as a barrier
ReactJS uses JSX. It's a syntax extension that allows HTML with JavaScript mixed
together. This approach has its own benefits, but some members of the development
community consider JSX as a barrier, especially for new developers. Developers
complain about its complexity in the learning curve.
ReactDOM
ReactJS is a library to build active User Interfaces thus rendering is one of the integral
parts of ReactJS. React provides the developers with a package react-dom a.k.a
ReactDOM to access and modify the DOM. Let’s see in brief what is the need of
having the package.
What is DOM?
Before React, Developers directly manipulated the DOM elements which resulted in
frequent DOM manipulation, and each time an update was made the browser had to
recalculate and repaint the whole view according to the particular CSS of the page,
which made the total process to consume a lot of time. As a betterment, React brought
into the scene the virtual DOM. The Virtual DOM can be referred to as a copy of the
actual DOM representation that is used to hold the updates made by the user and
finally reflect it over to the original Browser DOM at once consuming much lesser
time.
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.
render()
findDOMNode()
unmountComponentAtNode()
hydrate()
createPortal()
Pre-requisite: To use the ReactDOM in any React web app we must first import
ReactDOM from the react-dom package by using the following code snippet:
render() Function
This is one of the most important methods of ReactDOM. This function is used to
render a single React Component or several Components wrapped together in a
Component or a div element. This function uses the efficient methods of React for
updating the DOM by being able to change only a subtree, efficient diff methods, etc.
Syntax:
Return Type: This function returns a reference to the component or null if a stateless
component was rendered.
findDOMNode() Function
This function is generally used to get the DOM node where a particular React
component was rendered. This method is very less used like the following can be
done by adding a ref attribute to each component itself.
Syntax:
ReactDOM.findDOMNode(component)
Parameters: This method takes a single parameter component that expects a React
Component to be searched in the Browser DOM.
Return Type: This function returns the DOM node where the component was
rendered on success otherwise null.
unmountComponentAtNode() Function
This function is used to unmount or remove the React Component that was rendered
to a particular container. As an example, you may think of a notification component,
after a brief amount of time it is better to remove the component making the web page
more efficient.
10
Syntax:
ReactDOM.unmountComponentAtNode(container)
Parameters: This method takes a single parameter container which expects the DOM
container from which the React component has to be removed.
hydrate() Function
This method is equivalent to the render() method but is implemented while using
server-side rendering.
Syntax:
Return Type: This function attempts to attach event listeners to the existing markup
and returns a reference to the component or null if a stateless component was
rendered.
createPortal() Function
Syntax:
ReactDOM.createPortal(child, container)
11
container: This parameter expects the container in which the element has to
be rendered.
JSX
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures)
in the same file where you write JavaScript code, then preprocessor will transform
these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a
tag name, attributes, and children.
Example
Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code
which transforms by preprocessor(babel).
JSX File
1. <div>Hello JavaTpoint</div>
Corresponding Output
The above line creates a react element and passing three arguments inside where
the first is the name of the element which is div, second is the attributes passed in the
div tag, and last is the content you pass which is the "Hello JavaTpoint."
12
To use more than one element, you need to wrap it with one container element. Here,
we use div as a container element which has three nested elements inside it.
App.JSX
Output:
JSX Attributes
JSX use attributes with the HTML elements same as regular HTML. JSX uses
camelcase naming convention for attributes rather than standard naming convention
of HTML such as a class in HTML becomes className in JSX because the class is
the reserved keyword in JavaScript. We can also use our own custom attributes in
JSX. For custom attributes, we need to use data- prefix. In the below example, we
have used a custom attribute data-demoAttribute as an attribute for the <p> tag.
Example
13
6. <h1>JavaTpoint</h1>
7. <h2>Training Institutes</h2>
8. <p data-demoAttribute = "demo">This website contains the best CS tu
torials.</p>
9. </div>
10. );
11. }
12. }
13. export default App;
Example
Output:
JavaTpoint
This website contains the best CS tutorials.
Example
14
7. </div>
8. );
9. }
10. }
11. export default App;
Output:
45
JSX Comments
JSX allows us to use comments that begin with /* and ends with */ and wrapping
them in curly braces {} just like in the case of JSX expressions. Below example
shows how to use comments in JSX.
Example
JSX Styling
React always recommends to use inline styles. To set inline styles, you need to use
camelCase syntax. React automatically allows appending px after the number value
on specific elements. The following example shows how to use styling in the element.
Example
15
12. </div>
13. );
14. }
15. }
16. export default App;
Output:
Example
Output:
False!
Components
Earlier, the developers write more than thousands of lines of code for developing a
single page application. These applications follow the traditional DOM structure, and
making changes in them was a very challenging task. If any mistake found, it
manually searches the entire application and update accordingly. The
component-based approach was introduced to overcome an issue. In this approach,
the entire application is divided into a small logical group of code, which is known as
components.
16
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.
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. function 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.
17
Example
Output:
18
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.
The class component is also known as a stateful component because they can hold or
manage local state. It can be explained in the below example.
Example
In this example, we are creating the list of unordered elements, where we will
dynamically insert StudentName for every object from the data array. Here, we are
using ES6 arrow syntax (=>) which looks much cleaner than the old JavaScript syntax.
It helps us to create our elements with fewer lines of code. It is especially useful when
we need to create a list with a lot of items.
19
24. <ul>
25. {this.state.data.map((item) => <List data = {item} />)}
26. </ul>
27. </div>
28. );
29. }
30. }
31. class StudentName extends React.Component {
32. render() {
33. return (
34. <div>
35. <h1>Student Name Detail</h1>
36. </div>
37. );
38. }
39. }
40. class List extends React.Component {
41. render() {
42. return (
43. <ul>
44. <li>{this.props.data.name}</li>
45. </ul>
46. );
47. }
48. }
49. export default App;
Output:
Properties
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 gives
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.
20
Props are immutable so we cannot modify the props from inside the component.
Inside the components, 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.
When you need immutable data in the component, you have to add props to
reactDom.render() method in the main.js file of your ReactJS project and used it
inside the component in which you need. It can be explained in the below example.
Example
App.js
Main.js
Default Props
It is not necessary to always add props in the reactDom.render() element. You can
also set default props directly on the component constructor. It can be explained in
the below example.
Example
App.js
21
5. <div>
6. <h1>Default Props Example</h1>
7. <h3>Welcome to {this.props.name}</h3>
8. <p>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad.</p>
9. </div>
10. );
11. }
12. }
13. App.defaultProps = {
14. name: "JavaTpoint"
15. }
16. export default App;
Main.js
It is possible to combine both state and props in your app. You can set the state in the
parent component and pass it in the child component using props. It can be shown in
the below example.
Example
App.js
22
19. return (
20. <div>
21. <h1>State & Props Example</h1>
22. <h3>Welcome to {this.props.jtpProp}</h3>
23. <p>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad.</p>
24. </div>
25. );
26. }
27. }
28. export default App;
Main.js
Fetch API
we will know how we fetch the data from API (Application Programming Interface).
For the data, we have used the API endpoint from
http://jsonplaceholder.typicode.com/users we have created the component in App.js
and styling the component in App.css. From the API we have target “id”, “name”,
“username”, “email” and fetch the data from API endpoints. Below is the stepwise
implementation of how we fetch the data from an API in react. We will use the fetch
function to get the data from the API.
Step 2: Change your directory and enter your main folder charting as
23
cd MY-APP
https://jsonplaceholder.typicode.com/users
Step 4: Write code in App.js to fetch data from API and we are using fetch
function.
Project Structure
Example:
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false
};
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch(
"https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
24
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Pleses wait some time.... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ol key = { item.id } >
User_Name: { item.username },
Full_Name: { item.name },
User_Email: { item.email }
</ol>
))
}
</div>
);
}
}
.App {
text-align: center;
color: Green;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
25
}
to {
transform: rotate(360deg);
}
}
Step to run the application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/
The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over
time can happen as a response to user action or system event. A component with the
state is known as stateful components. It is the heart of the react component which
determines the behavior of the component and how it will render. They are also
responsible for making a component dynamic and interactive.
A state must be kept as simple as possible. It can be set by using the setState()
method and calling setState() method triggers UI updates. 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. To set an initial state before any interaction
occurs, we need to use the getInitialState() method.
For 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.
Defining State
To define a state, you have to first 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.
Example
The below sample code shows how we can create a stateful component using ES6
syntax.
26
7. render() {
8. const bio = this.state.displayBio ? (
9. <div>
10. <p><h3>Javatpoint is one of the best Java training institute in Noid
a, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced
Java developers and trainers from multinational companies to teach our camp
us students.</h3></p>
11. </div>
12. ) : null;
13. return (
14. <div>
15. <h1> Welcome to JavaTpoint!! </h1>
16. { bio }
17. </div>
18. );
19. }
20. }
21. export default App;
To set the state, it is required to call the super() method in the constructor. It is
because this.state is uninitialized before the super() method has been called.
We can change the component state by using the setState() method and passing a new
state object as the argument. Now, create a new method toggleDisplayBio() in the
above example and bind this keyword to the toggleDisplayBio() method otherwise we
can't access this inside toggleDisplayBio() method.
1. this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking on
this button triggers the toggleDisplayBio() method which displays the desired output.
27
When you click the Read More button, you will get the below output, and when you
click the Show Less button, you will get the output as shown in the above image.
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.
28
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.
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.
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.
componentDidMount()
This is invoked immediately after a component gets rendered and placed on
the DOM. Now, you can do 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.
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.
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.
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.
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.
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
29
inside render() will be invoked again to ensure that the component displays
itself properly.
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.
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
30
29. }
30. shouldComponentUpdate(newProps, newState) {
31. return true;
32. }
33. componentWillUpdate(nextProps, nextState) {
34. console.log('Component Will UPDATE!');
35. }
36. componentDidUpdate(prevProps, prevState) {
37. console.log('Component Did UPDATE!')
38. }
39. componentWillUnmount() {
40. console.log('Component Will UNMOUNT!')
41. }
42. }
When you click on the Click Here Button, you get the updated result which is shown
in the below screen.
JS Localstorage
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');
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.
31
Example
App.jsx
32
</div>
);
};
export default App;
In the above example, when the Done button is clicked, the handle function is
executed which will set the items in the localStorage of the user and display it. But
when the Remove button is clicked, the remove function is executed which will
remove the items from the localStorage.
Output
Events
Just like HTML DOM events, React can perform actions based on user events.
React has the same events as HTML: click, change, mouseover etc.
Adding Events
33
React:
HTML:
Example:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Passing Arguments
Example:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
34
Event handlers have access to the React event that triggered the function.
Example:
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Lifting State Up
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.
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).
35
Problem: Let’s Implement this with a simple but general example. We are
considering the second example.
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:
After:
Filename- A.js:
36
constructor(props) {
super(props);
this.handleTextChange = this.handleTextChange.bind(this);
this.state = {text: ''};
}
handleTextChange(newText) {
this.setState({text: newText});
}
render() {
return (
<React.Fragment>
<B text={this.state.text}
handleTextChange={this.handleTextChange}/>
<C text={this.state.text} />
</React.Fragment>
);
}
}
export default A;
Filename- B.js:
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;
37
Filename- C.js:
render() {
return (
<h3>Output: {this.props.text}</h3>
);
}
}
export default C;
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 −
Inheritance
This sis simple to just input the name. We will have two more components to create
and update the username field.
38
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'));
Composition
39
render() {
return (
<div>
< UserNameForm />
<button>Update</button>
</div>
)
}}ReactDOM.render(
(<div>
<CreateUserName />
<UpdateUserName />
</div>), document.getElementById('root'));
Use of composition is simpler than inheritance and easy to maintain the complexity.
40