Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views16 pages

FSD 2 3 ReactNotes

Uploaded by

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

FSD 2 3 ReactNotes

Uploaded by

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

UNIT-II

CHAPTER -3
REACT
CONTENTS

1. Introduction
2. React Components
3. React Classes
4. Composing Components
5. Passing data using Properties & Children
6. Dynamic Composition
7. React state- Initial state
8. Async state initialization
9. References
1. 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 which is responsible only
for the view layer of the application.
It was initially developed and maintained by Facebook and later used in its
products like WhatsApp & Instagram.
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.
How to create react app?
 write React components that correspond to various elements
 organize these components inside higher level components which define the
application structure.
Why learn ReactJS?
Many Javascript frameworks like Angular,Node, follow tradition data structure
which uses DOM. 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.
Whereas 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 Document Object Model (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. Due to this,
when we write a React component, we did not write directly to the DOM; instead,
we are writing virtual components that react will turn into the DOM.
Ways to install ReactJS?
There are two ways to set up an environment for successful ReactJS application.
They are given below.
1. Using the npm command
2. Using the create-react-app command

The create-react-app is an excellent tool for beginners, which allows you to create
and run React project very quickly. It does not take any configuration manually.
This tool is wrapping all of the required dependencies like Webpack, Babel for
React project itself and then you need to focus on writing React code only.

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

To check versions run below commands in the command prompt


Command to check node version : node –v
Command to check npm version : npm -v
Step 1: Install create-react-app by running the command

npm install –g create-react-app

Step 2 – Create new React project

create-react-app reactproject

The above command will take some time to install the React and create a new project
with the name "reactproject." Now, we can see the terminal as like below.
The above screen tells that the React project is created successfully on our system.
Now, start the server so that we can access the application on the browser.
C:\Users\dell\reactproject>npm start
NPM is a package manager which starts the server in development mode and
access the application at default port http://localhost:3000. Now, we will get the
following screen.

To stop the server , type Ctrl+C.

Features of React:
1. JSX- Javascript XML which allows to embed javascript objects into HTML
Ex: const name = "REACT";
const ele = <h1>Welcome to {name}</h1>;

2. Components - ReactJS application is made up of multiple components, and


each component has its own logic and controls.
3. Virtual DOM - A virtual DOM object is a representation of the original
DOM object. 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.
4. One way Data Binding
5. Simplicity

React Render HTML


React renders HTML to the web page by using a function called createRoot() and
its method render().
createRoot() function takes one argument, an HTML element.
Syntax: createRoot(document.getElementById(“id”);
The purpose of the function is to define the HTML element where a React
component should be displayed.
render() method is called to render the React component.
Ex:
const element = ReactdOM.createRoot(document.getElementById(“id”);
element.render(<App/>);

JSX(Javascript Extensible Markup Language):


• React JSX helps us to write HTML in JavaScript and forms the basis of
React Development.
• JSX allows us to write HTML elements in JavaScript and place them in the
DOM without any createElement() or appendChild() methods.
• Like XML/HTML, JSX tags have a tag name, attributes, and children.
• JSX syntax is used by preprocessors (i.e., transpilers like babel) to transform
HTML-like syntax into standard JavaScript objects that a JavaScript engine
will parse.
Ex:
JSX : const element = <div>ReactJS</div>
After preprocessing by Babel:
React.createElement(“div”,null,”ReactJS” );
First argument is the element, second argument is the attributes, and the last
is the content within that element.
In JSX, HTML code must be wrapped in one top level element and must be
properly closed.
Ex:
<div>REACTJS</div>
<h1>welcome</h1>
<h1>Learn REACT</h1>
</div>
Alternative way to avoid unnecessary element only for wrapping, we can use a
“fragment” to wrap multiple lines.
<>
<h1>welcome</h1>
<h1>Learn REACT</h1>
</>

2. REACT COMPONENTS
The component based approach is introduced to overcome the issue of making
changes in single page applications.
React Components are the building blocks of React Application. They are the
reusable code blocks containing logics and and UI elements. They have the same
purpose as JavaScript functions and return HTML. Components make the task of
building UI much easier.
A UI is broken down into multiple individual pieces called components which
works independently and then merge them all into a parent component which will
be the final UI.
Every React component have their own structure, methods as well as APIs.
They can be reusable as per the 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.

When creating a React component, the component's name must start with an upper
case letter.
In React, there are two types of components:
1. Functional Components
2. Class Components
Before discussing about types of components, let’s learn about React Classes.
3. React Classes
React classes are used to create real components.
These classes can be reused within other components, handle events and so much
more.
React classes are created by extending React.Component which is the base class
from which all custom classes must be derived.
Within the class definition, a render() method must be defined. This method is
what React calls when it needs to display the component in the UI. Without this
method, component will not seen on the UI. This function is supposed to return
an JSX element or instance of another react component.
These components are termed as ClassComponents.
ES6 Class
Properties JSX
(props) (State)

Ex:
class ClassComponent extends React.Component {
render() {
return <h1>This is a Class Component</h1>;
}
}

Class can be instantiated by


const element = <ClassComponent/>

Functional Components:
Functional components are just like JavaScript functions that accept properties
and return a React element.
Functional components can be created by writing a JavaScript function.

Properties Javascript function JSX


(props)

Ex:
function Welcome() {
return (<h1>
Welcome Message!
</h1>);
}

const Welcome=()=> <h1>Welcome Message!</h1>


4. Composing Components
Component composition in React involves combining smaller, independent
components to create complex UIs.
Each sub-component can contain further components, enhancing code readability.
Component Composition enhances performance in software development.
How?
 Code Reusability
 Modularity
 Optimized Code Loading
 Parallel Development

Few things to remember when composing components:


 Larger components can be split into smaller components when there is a
logical separation possible
 When there is a possibility for reuse, components can be built which take
in different inputs from different callers
 Coupling between components should be minimal.

5. Passing Data Using Properties & Children

React components use props to communicate with each other.


Every parent component can pass some information to its child children by giving
them props.
The easiest way to pass data to child components is using an attribute while
instantiating a component.
Ex: <App msg=”Welcome React”/>
Within the render() method of the child component, the attribute’s value can be
accessed via a special object variable called props, which is available via the this
accessor.
Ex: <h1>this.props.msg</h1>
Not only simple string, but can also pass any javascript value including objects,
arrays, functions.
Passing data using children:
Another way to pass data to other component is by using the content of the HTML
like node of the component. Such data can be accessed using a special field of
this.props.children.
Ex:
<App>
This is passed as content to the component
</App>

class App extends React.Component{


render(){
return(
<h1>
{this.props.children}
</h1>
)
}
}

Data can be passed as array. If more lines are passed as content to the component,
they can be accessed as array elements.
Ex: this.props.children[0];
6. Dynamic Composition
Instead of hard-coding, data can also passed to component dynamically.
Ex:
studentlist.js
import React from 'react'
class Row extends React.Component{
render(){
const student=this.props.student;
const style=this.props.style;
return(
<tr>
<td style={style}>{student.id}</td>
<td style={style}>{student.name}</td>
<td style={style}>{student.branch}</td>
</tr>
);
}
}
class Student extends React.Component{
render(){
const style={border:"1px solid"};
const students=this.props.students;
const rows=students.map(student => <Row style={style} student={student}/>);
return(
<table style={style}>
<tr>
<th style={style}>RollNo</th>
<th style={style}>Name</th>
<th style={style}>Branch</th>
</tr>
{rows}
</table>
);
}
}
export default Student;

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import StudentComp from './components/studentList';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
const studentsList=[
{id:501,name:"Madhu",branch:"CSE"},
{id:502,name:"Ameens",branch:"CSE"},
{id:401,name:"Sudha",branch:"ECE"}
]
root.render(
<>
<StudentComp students= {studentsList}></StudentComp>
</>
);
7. React State
The state is an updatable structure that is used to contain data or information about
the component.
A component with the state is known as stateful component.
This state needs to be used in the render() method to build the view.
When data or the state changes, React automatically rerenders the view to show the
new changed data.
The state of a component is captured in a variable called this.state in the
component’s class, which can consist of more than one key-value pairs.

What type of data can be included in the state?


Data that affects the rendered view and can change due to any event.
Life Cycle of React Components:
1. Initialization: This is the stage where the component is constructed with
props and default state . This is done in the Constructor of the Component
class.
2. Mounting: Returning the JSX element by the render method. Two more
methods in addition to render() in this phase, componentWillMount() and
componentDidMount().
3. Updating: Updation is the phase where the states and props of a component
are updated followed by some user events such as clicking, pressing a key
on the keyboard, etc. Methods invoked in this stage are
ComponentWillReceiveProps(), shouldComponentUpdate(),
componentWillUpdate(), componentDidUpdate().
4. Unmounting: unmounting the component from DOM. Method that can be
invoked in this phase, componentWillUnmount().

Initial state:
Setting the initial state needs to be done in constructor.
This can be done by simply assigning the variable this.state.
Ex: this.state={color:red};
8. Async State Initialization
The state can only be assigned a value in the constructor. After that, the state can
be modified.

The state can be modified by the method this.setState(), which takes one argument
which is an object containing all the changed state variables and their values.

import React from 'react';

class CompWithState extends React.Component{


constructor(){
super();
this.state={color:"red", style:{color:"red"}};
this.changeColor=this.changeColor.bind(this);
}
changeColor(){
this.setState({color:"blue", style:{color:"blue"}})
}
render(){
return(
<>
<h1 style={this.state.style}>I like {this.state.color} color.</h1>
<button type="button" id="btn" onClick={this.changeColor}>Change Color</button>
</>
)
}
}

export default CompWithState;

Using State in Functional Components:


Even though functional components are stateless components, state can be set in a
component so that it can work as class component.
To use state, Hooks are used.
To set state in functional component, useState component should be imported
from react
import {useState} from ‘react’;
in the function before render method set the state
const [color, setColor] = useState(“red”);
color - state variable
setColor - the method with which the state variable can be modified
useState(“red”) – default value red is set to the variable color

Ex:
import {useState} from 'react';
function FavColor(){
const [color,setColor] = useState("red");
return(
<>
<h1>I like {color}.</h1>
<button onClick={()=>setColor("blue")}>Change Color</button>
</>
);
}
export default FavColor;

Differences between State and Props:

Attribute State Props

Mutability Can be changed using this.setState() Cannot be changed

Ownership Belongs to the component Belongs to ancestor

Information Model information Model information

Affects Rendering of the component Rendering of the component


9. References

1. TB3: Pro MERN Stack by Dr. Vasan Subramanian.


2. https://react.dev/learn
3. https://www.javatpoint.com/reactjs-tutorial
4. https://www.w3schools.com/react
5. https://www.geeksforgeeks.org/react-tutorial/?ref=lbp

You might also like