REACT JS
1. COMPONENTS
2. MODULES
3. Example code:-
import React from 'react';
import ReactDOM from 'react-dom/client';
function Greeting(props) {
return <h1>Welcome to TutorialsPoint</h1>;
const container = [Link]("root");
const root = [Link](container);
[Link](<Greeting />);
Everything is a component:
2 types:-
Function component
Class component
PROPS
Render method will be called for displaying any user define contents.
Modify the code to display roll number and name:
import React from 'react';
import ReactDOM from 'react-dom/client';
function Greeting(props) {
return <h1>Roll no:[Link].P2CSE25001<h1><BR>
<h2>Name:Archa biju</h2>;
}
const container = [Link]("root");
const root = [Link](container);
[Link](<Greeting />);
FEATURES
Virtual DOM- Virtual DOM is a special DOM created by React. Virtual
DOM represents the real DOM of the current HTML document.
Whenever there is a change in the HTML document, React checks the
updated virtual DOM with the previous state of the Virtual DOM and
update only the different in th actual / real DOM. This improves the
performance of the rendering of the HTML [Link] example, if we
create a React component to show the current time by periodically
updating the time through setInterval() method, then React will update
only the current time instead of updating the whole content of the
component.
Components- React is build upon the concept of components. All
modern front end framework relies on the component architecture.
Component architecture enables the developer to break down the large
application into smaller components, which can be further break down
into even smaller component. Breaking down the application into
smaller component simplifies the application and make it more
understandable and manageable.
JSX- JSX is a JavaScript extension to create arbitrary HTML element using
syntax similar to HTML. This will simplify the HTML document creation as
well as easy to understand the document. React will convert the JSX into
JavaScript object consisting of React's createElement() function call
before executing it. It improves the performance of the application. Also,
React allows the HTML document creation using
pure createElement() function without JSX as well. This enables the
developer to directly create HTML document in a situation where JSX
does not fit well.
One way data binding- One way data binding prevents the data in a
component to flow backward. A component can pass the data to its child
component only. The data cannot be passed by a component to its
parent component in any situation. This will simplify the data handling
and reduce the complexity. Two way data binding may seems mandatory
at first but a closer look suggests that the application can be done with
one way data binding only and this simplifies the application concept as
well.
Scalable- React can be used to create application of any size. React
component architecture, Virtual DOM and one way data binding
properly handle large application in a reasonable time frame required for
a front end application. These features make React a scalable solution.
Flexible- React only provides only few basic concept to create truly
scalable application. React does not restrict the developer in any way to
follow a rigid process. This enables the developer to apply their own
architecture on top the basic concept and makes it flexible.(USER
DEFINED COMPONENT).
Modular- React component can be created in a separate JavaScript file
and can be made exportable. This enables the developer to categories
and group certain components into a module so that it can be imported
and used wherever needed.(CONVERSION OF NUMBER TO WORDS)
ReactJS - Architecture
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8" /> <title>React Application</title>
</head>
<body>
<div id="react-app">
</div>
<script src="[Link]
crossorigin>
</script>
<script src="[Link]
[Link]" crossorigin>
</script>
<script language="JavaScript">
element = [Link]('h1', {}, 'Hello React!')
[Link](element, [Link]('react-
app'));
</script>
</body>
</html>
Next, serve the application using serve web server.
serve ./[Link]
CODE TO DISPLAY YOUR NAME AND UG DEGREE AND UG COLLEGE
NAME :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React Application</title>
</head>
<body>
<div id="react-app"></div>
<script src="[Link]
crossorigin></script>
<script src="[Link]
[Link]" crossorigin></script>
<script>
const element = [Link](
'div',
{},
[Link]('h1', {}, 'Name: Archa Biju'),
[Link]('h2', {}, 'UG Degree: [Link] in Information
Technology'),
[Link]('h3', {}, 'UG College: Government Engineering College,
Idukki')
);
// Render to the div with id="react-app"
[Link](element, [Link]('react-app'));
</script>
</body>
</html>
[Link]
import React from "react";
class HelloWorld extends [Link] { render()
{ return ( <div> <h1>Hello World!</h1> </div> );
}
} export default HelloWorld;
Modify the code using font tag
import React from "react";
class HelloWorld extends [Link] {
render() {
return (
<div>
<h1>
<font color="blue" face="Arial" size="6">
Hello World!
</font>
</h1>
</div>
);
}
}
export default HelloWorld;
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './components/HelloWorld';
[Link](
<[Link]>
<HelloWorld />
</[Link]>,
[Link]('root')
);
components
Function Components
Class Components
Function Components
A function component is literally defined as JavaScript functions. This
React component accepts a single object argument and returns a
React element. Note that an element in React is not a component, but
a component is comprised of multiple elements. Following is the syntax
for the function component in React:
function function_name(argument_name) {
function_body;
Class Components
Similarly, class components are basic classes that are made of multiple functions. All class
components of React are subclasses of the [Link] class, hence, a class
component must always extend it. Following is the basic syntax −
class class_name extends [Link] {
render() {
return <h1>Hello, {[Link]}</h1>;
}
Class components supports state management out of the box whereas function components
does not support state management. But, React provides a hook, useState() for the function
components to maintain its state.
Class component have a life cycle and access to each life cycle events through dedicated
callback apis. Function component does not have life cycle. Again, React provides a
hook, useEffect() for the function component to access different stages of the component.
Create a React component Bill info that displays details like:
Bill number
Bill name (vendor)
Date
Quantity
Total cost
Also add a new field named Category such that:
o If the bill value is between 1000 and 2000, category = A
o If the bill value is between 2001 and 3000, category = B
o If the bill value is greater than 3000, category = C
import React from 'react';
import './[Link]';
class Bill info extends [Link] {
render() {
// Sample data
const billNumber = 1;
const billName = "Vendor XYZ";
const date = "2020-10-10";
const quantity = 5;
const totalCost = 3000;
// Logic for Category
let category = "";
if (totalCost >= 1000 && totalCost <= 2000) {
category = "A";
} else if (totalCost >= 2001 && totalCost <= 3000) {
category = "B";
} else if (totalCost > 3000) {
category = "C";
}
return (
<div className="expense-item">
<div><b>Bill number:</b> <em>{billNumber}</em></div>
<div><b>Bill name (Vendor):</b> <em>{billName}</em></div>
<div><b>Date:</b> <em>{date}</em></div>
<div><b>Quantity:</b> <em>{quantity}</em></div>
<div><b>Total cost:</b> <em>{totalCost}</em></div>
<div><b>Category:</b> <em>{category}</em></div>
</div>
);
}
}
export default Billinfo;
NESTED COMPONENTS
A React component is made up of the multiple individual components. React
allows multiple components to be combined to create larger components. Also,
React components can be nested to any arbitrary level.
Extend the code to convert the amount scaled down by 10% . add a
function for the same.
import React from 'react';
import './[Link]';
class ExpenseEntryItem extends [Link] {
/**
* This function takes an amount and reduces it by 10%.
* Example: if amount = 3000 → returns 2700.
*/
getDiscountedAmount(amount) {
return amount - (amount * 0.10);
render() {
const billNumber = 1;
const billName = "Vendor XYZ";
const date = "2020-10-10";
const quantity = 5;
const totalCost = 3000;
let category = "";
if (totalCost >= 1000 && totalCost <= 2000) {
category = "A";
} else if (totalCost >= 2001 && totalCost <= 3000) {
category = "B";
} else if (totalCost > 3000) {
category = "C";
const discountedCost = [Link](totalCost);
return (
<div className="expense-item">
<div><b>Bill number:</b> <em>{billNumber}</em></div>
<div><b>Bill name (Vendor):</b> <em>{billName}</em></div>
<div><b>Date:</b> <em>{date}</em></div>
<div><b>Quantity:</b> <em>{quantity}</em></div>
<div><b>Total cost:</b> <em>{totalCost}</em></div>
<div><b>Category:</b> <em>{category}</em></div>
<div><b>Total cost after 10% discount:</b>
<em>{discountedCost}</em></div>
</div>
);
export default ExpenseEntryItem;
create an another component named display rupees within the
component. take the number and display the unit digits in rupees.
import React from 'react';
import './[Link]';
// Child component to display the unit digit of a number in Rupees
class DisplayRupees extends [Link] {
render() {
const { amount } = [Link];
const unitDigit = amount % 10; // extract unit digit
return (
<div>
<b>Unit Digit in Rupees:</b> <em>{unitDigit} Rupees</em>
</div>
);
class BillInfo extends [Link] {
getDiscountedAmount(amount) {
return amount - (amount * 0.10);
render() {
// Sample bill data
const billNumber = 1;
const billName = "Vendor XYZ";
const date = "2020-10-10";
const quantity = 5;
const totalCost = 3000;
// Category logic
let category = "";
if (totalCost >= 1000 && totalCost <= 2000) {
category = "A";
} else if (totalCost >= 2001 && totalCost <= 3000) {
category = "B";
} else if (totalCost > 3000) {
category = "C";
// 10% reduced amount
const discountedCost = [Link](totalCost);
return (
<div className="bill-info">
<div><b>Bill number:</b> <em>{billNumber}</em></div>
<div><b>Bill name (Vendor):</b> <em>{billName}</em></div>
<div><b>Date:</b> <em>{date}</em></div>
<div><b>Quantity:</b> <em>{quantity}</em></div>
<div><b>Total cost:</b> <em>{totalCost}</em></div>
<div><b>Category:</b> <em>{category}</em></div>
<div><b>Total cost after 10% discount:</b>
<em>{discountedCost}</em></div>
<DisplayRupees amount={totalCost} />
</div>
);
export default BillInfo;
extend the code to display the numbers in words
import React from 'react';
import './[Link]';
/**
* 👉 Small helper component
* This just takes a number and shows the *last digit* as "Rupees".
* Example: 305 → "5 Rupees"
*/
class DisplayRupees extends [Link] {
render() {
const { amount } = [Link];
const unitDigit = amount % 10; // find the last digit
return (
<div>
<b>Unit Digit in Rupees:</b> <em>{unitDigit} Rupees</em>
</div>
);
class BillInfo extends [Link] {
getDiscountedAmount(amount) {
return amount - (amount * 0.10);
numberToWords(num) {
const ones = [
"", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
];
const tens = [
"", "", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"
];
if (num === 0) return "Zero";
if (num < 20) return ones[num];
if (num < 100) return tens[[Link](num / 10)] + (num % 10 !== 0 ? " " +
ones[num % 10] : "");
if (num < 1000) {
return ones[[Link](num / 100)] + " Hundred " + (num % 100 !== 0 ?
[Link](num % 100) : "");
if (num < 100000) {
return [Link]([Link](num / 1000)) + " Thousand " + (num
% 1000 !== 0 ? [Link](num % 1000) : "");
return [Link](); // fallback
}
render() {
const billNumber = 1;
const billName = "Vendor XYZ";
const date = "2020-10-10";
const quantity = 5;
const totalCost = 3000;
let category = "";
if (totalCost >= 1000 && totalCost <= 2000) {
category = "A";
} else if (totalCost >= 2001 && totalCost <= 3000) {
category = "B";
} else if (totalCost > 3000) {
category = "C";
const discountedCost = [Link](totalCost);
return (
<div className="bill-info">
<h2>🧾 Bill Information</h2>
<div><b>Bill number:</b> <em>{billNumber}</em></div>
<div><b>Bill name (Vendor):</b> <em>{billName}</em></div>
<div><b>Date:</b> <em>{date}</em></div>
<div><b>Quantity:</b> <em>{quantity}
({[Link](quantity)})</em></div>
<div><b>Total cost:</b> <em>{totalCost}
({[Link](totalCost)})</em></div>
<div><b>Category:</b> <em>{category}</em></div>
<div>
<b>Total cost after 10% discount:</b>
<em> {discountedCost} ({[Link](discountedCost)})</em>
</div>
{/* Extra small detail */}
<DisplayRupees amount={totalCost} />
</div>
);
export default BillInfo;
1)write a program to print natural number
import React from 'react';
function NaturalNumberPrinter({ limit }) {
const numbers = [];
for (let i = 1; i <= limit; i++) {
[Link](i);
}
return (
<div>
<h2>Natural Numbers up to {limit}</h2>
<ul>
{[Link]((num) => (
<li key={num}>{num}</li>
))}
</ul>
</div>
);
}
export default NaturalNumberPrinter;
OUTPUT:
Natural Numbers (1 to 10)
1
2
3
4
5
6
7
8
9
10
2)write a program to check whether the number is a Armstrong
number or not
import React, { useState } from 'react';
function ArmstrongChecker() {
const [number, setNumber] = useState('');
const [isArmstrong, setIsArmstrong] = useState(null);
const checkArmstrong = () => {
const num = parseInt(number);
if (isNaN(num) || num < 0) {
setIsArmstrong(null); // Reset if invalid input
return;
}
const numStr = [Link]();
const order = [Link];
let sum = 0;
for (let i = 0; i < order; i++) {
const digit = parseInt(numStr[i]);
sum += [Link](digit, order);
}
setIsArmstrong(sum === num);
};
return (
<div>
<h2>Armstrong Number Checker</h2>
<input
type="number"
value={number}
onChange={(e) => setNumber([Link])}
placeholder="Enter a number"
/>
<button onClick={checkArmstrong}>Check</button>
{isArmstrong !== null && (
<p>
{number} is {isArmstrong ? 'an Armstrong number' : 'not an
Armstrong number'}.
</p>
)}
</div>
);
}
export default ArmstrongChecker;
OUTPUT:
Armstrong Number Checker
Check
153 is an Armstrong number.
[Link] a code for factorial of a given number
import React, { useState } from "react";
function Factorial() {
const [num, setNum] = useState(5); // default input = 5
const [result, setResult] = useState(null);
// Recursive factorial function
const factorial = (n) => {
if (n === 0 || n === 1) return 1; // base case
return n * factorial(n - 1); // recursion
};
const handleClick = () => {
if (num < 0) {
setResult("Factorial not defined for negative numbers");
} else {
setResult(factorial(num));
}
};
return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h1>Factorial Calculator</h1>
{/* Input box */}
<input
type="number"
value={num}
onChange={(e) => setNum(Number([Link]))}
style={{ padding: "5px", margin: "10px" }}
/>
{/* Button */}
<button onClick={handleClick} style={{ padding: "5px 15px" }}>
Calculate
</button>
{/* Display result */}
<div style={{ marginTop: "20px", fontSize: "18px" }}>
{result !== null ? <p>Factorial of {num} = {result}</p> : "Enter a
number and click Calculate"}
</div>
</div>
);
}
export default Factorial;
OUTPUT:
Factorial Calculator
Calculate
Factorial of 5 = 120
4)Greatest of three numbers
import React, { useState } from "react";
function GreatestNumber() {
const [num1, setNum1] = useState(0);
const [num2, setNum2] = useState(0);
const [num3, setNum3] = useState(0);
const [greatest, setGreatest] = useState(null);
const findGreatest = () => {
const max = [Link](num1, num2, num3);
setGreatest(max);
};
return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h1>Greatest of Three Numbers</h1>
{/* Inputs */}
<input
type="number"
value={num1}
onChange={(e) => setNum1(Number([Link]))}
style={{ margin: "5px", padding: "5px" }}
placeholder="Enter first number"
/>
<input
type="number"
value={num2}
onChange={(e) => setNum2(Number([Link]))}
style={{ margin: "5px", padding: "5px" }}
placeholder="Enter second number"
/>
<input
type="number"
value={num3}
onChange={(e) => setNum3(Number([Link]))}
style={{ margin: "5px", padding: "5px" }}
placeholder="Enter third number"
/>
{/* Button */}
<div>
<button
onClick={findGreatest}
style={{ marginTop: "10px", padding: "5px 15px" }}
>
Find Greatest
</button>
</div>
{/* Result */}
<div style={{ marginTop: "20px", fontSize: "18px" }}>
{greatest !== null ? (
<p>Greatest Number is: {greatest}</p>
):(
"Enter numbers and click Find Greatest"
)}
</div>
</div>
);
}
export default GreatestNumber;
OUTPUT:
Greatest of Three Numbers
Find Greatest
Greatest Number is: 23
5)There are 4 boxes labelled as A,B,C,D .Box A has violet colour
balls , B has orange colour balls, Box C has cream colour balls and
Box D has white colour balls. Each Box is filled with number of balls
which is twice based on the order the initial value Is set by the user.
The game checker has 3 choices 1,2,3.
On choice 1each Box will be filled twice the number of balls .
On choice 2 the consecutive boxes are made empty and push to the
last box.
On choice 3 all odd number boxes will be pushed into the even
numbered boxes.
Display the number of balls with each colour across the boxes.
import React, { useState } from "react";
function BoxesGame() {
const [initial, setInitial] = useState(1);
const [boxes, setBoxes] = useState([0, 0, 0, 0]); // A, B, C, D
const initializeBoxes = () => {
let A = initial;
let B = A * 2;
let C = B * 2;
let D = C * 2;
setBoxes([A, B, C, D]);
};
const choice1 = () => {
setBoxes([Link]((val) => val * 2));
};
const choice2 = () => {
let total = boxes[0] + boxes[1] + boxes[2] + boxes[3];
setBoxes([0, 0, 0, total]);
};
const choice3 = () => {
let [A, B, C, D] = boxes;
B += A; // A to B
D += C; // C to D
A = 0;
C = 0;
setBoxes([A, B, C, D]);
};
return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h1> Box Game Checker</h1>
type="number"
value={initial}
onChange={(e) => setInitial(Number([Link]))}
style={{ padding: "5px", margin: "10px" }}
/>
<button onClick={initializeBoxes} style={{ padding: "5px 15px" }}>
Initialize Boxes
</button>
<div style={{ margin: "20px" }}>
<button onClick={choice1} style={{ margin: "5px", padding: "5px
15px" }}>
Choice 1: Double All
</button>
<button onClick={choice2} style={{ margin: "5px", padding: "5px
15px" }}>
Choice 2: Empty A,B,C → Push to D
</button>
<button onClick={choice3} style={{ margin: "5px", padding: "5px
15px" }}>
Choice 3: Odd → Even
</button>
</div>
<div style={{ marginTop: "20px", fontSize: "18px" }}>
<p style={{ color: "violet" }}>Box A (Violet): {boxes[0]}</p>
<p style={{ color: "orange" }}>Box B (Orange): {boxes[1]}</p>
<p style={{ color: "peru" }}>Box C (Cream): {boxes[2]}</p>
<p style={{ color: "gray" }}>Box D (White): {boxes[3]}</p>
</div>
</div>
);
}
export default BoxesGame;
OUTPUT:
Box Game Checker
Initialize Boxes
Choice 1: Double AllChoice 2: Empty A,B,C → Push to DChoice 3: Odd → Even
Box A (Violet): 4
Box B (Orange): 8
Box C (Cream): 16
Box D (White): 32
[Link] details about urself using reactjs
[Link] the electricity bill form in reactjs for next class
[Link] calculator- in props reactjs
ReactJS - Properties (props)
[Link]
React properties supports attribute's value of different types. They are as follows,
String
Number
Datetime
Array
List
Objects
When we need immutable data in our component, we can just add props
to [Link]() function in [Link] and use it inside our component.
Add props to [Link]
[Link]
import React from 'react';
class App extends [Link] {
render()
{ return (
<div>
<h1>{[Link]}</h1>
<h2>{[Link]}</h2>
</div> );
export default App;
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import App from './[Link]';
[Link](<App headerProp = "Header from props..." contentProp = "Content
from props..."/>, [Link]('app'));
export default App;
ReactJS - Create a Component Using Properties
if a component is defined as a function or class, it must act like
a pure function with respect to their properties.
the Props passed to a component are Read-Only.
But as the application UIs are dynamic and change their inputs
over time, we use "state" concept to handle it.
Qn: Create a fee tracker for passengers applying for visa
The visa charge is 4 times the order of the countries .
Base cost is 3000 rupees
[Link]
[Link]
[Link]
[Link]
[Link]
Create a form and calculate the cost for filing the visa
constructor(props) {
super(props);
}
render() {
return (
<div>
<div><b>PASSENGERID:</b><em>{[Link]}</em></div>
<div><b> FILING DATE:</b> <em>{[Link] date}</em></div>
<div><b>COUNTRY:</b> <em>{[Link] }</em></div>
<div><b>VISA COST:</b> <em>{[Link] ()}</em></div>
</div>
);
[Link]
import React from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';
import App from './App';
const root = [Link]([Link]('root'));
[Link](
<[Link]>
<App />
</[Link]>
);
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import VisaCalculator from './components/VisaCalculator'
const name = "passengerid"
const filingDate = new Date("2020-10-10")
const country = “country”
const visacost = "Visacost"
[Link](
<[Link]>
<VisaCalculator
name={name}
amount={amount}
spendDate={spendDate}
category={category} />
</[Link]>,
[Link]('root')
);
Qn: Create a form for calculating the discount for the product there are
4 categories
Category A:5%
Category B:3%
Category C:2%
Category D:1%
Calculate the discount percentage assuming the product category is
given in a static manner.(have to do for next class)
Extend the same code where the discount is calculated dynamically
COMPONENT LIFE CYCLE
Mounting - Mounting represents the rendering of the React component
in the given DOM node.
Updating - Updating represents the re-rendering of the React
component in the given DOM node during state changes / updates.
Unmounting - Unmounting represents the removal of the React
component.
EVENT MANAGEMENT
Mouse Events
Keyboard Events
Focus Events
Synthetic React Events - Disadvantage: Consumes a lot of CPU memory
Handling an Event
log = () => {
[Link]("Event is fired");
}
Passing Arguments to Event Handler
1. Arrow Method
2. Bind Method - bind the event handler method in the
constructor of the component.
FORM PROGRAMMING:
(VIVA AND QUIZ)
Controlled component − In controlled component, React provides a
special attribute, value for all input elements and controls the input
elements. The value attribute can be used to get and set the value of the
input element. It has to be in sync with state of the component.
Uncontrolled component − In uncontrolled component, React provides
minimal support for form programming. It has to use “Ref concept”
“(another react concept to get a DOM element in the React component
during runtime) to do the form programming.
Step 1 − Create a form element.
<input type="text" name="CyberPulse " />
Step 2 − Create a state for input element.
[Link] = {
CyberPulse : ''
}
Step 3 − Add a value attribute and assign the value from state.
<input type="text" name=" CyberPulse " value={[Link].
CyberPulse } />
Step 4 − Add a onChange attribute and assign a handler method.
<input type="text" name=" CyberPulse " value={[Link]. CyberPulse }
onChange={[Link] CyberPulse Change} />
Step 5 − Write the handler method and update the state whenever the
event is fired.
handle CyberPulse Change(e) {
[Link]({
CyberPulse = [Link]
});
}
Step 6 − Bind the event handler in the constructor of the component.
[Link] = [Link](this)
Finally, get the input value using username from [Link] during
validation and submission.
handleSubmit(e) {
[Link]();
alert([Link]);
}