Client-Side Scripting
Comprehensive Study Notes
Units I – V | AngularJS, React, JavaScript, AJAX, JSON
Covers all TLOs with syntax, examples, and exam-ready explanations
Unit I: Fundamentals of Client-Side Scripting
1.1 Introduction to Scripting
Basic Web Architecture
The web follows a Client-Server model:
• Client: The user's browser (Chrome, Firefox, etc.) that requests and displays web content.
• Server: A remote computer that stores web pages, databases, and runs server-side logic.
• Protocol: HTTP/HTTPS is used for communication between client and server.
When a user types a URL:
• Browser sends an HTTP Request to the server.
• Server processes and sends back an HTTP Response (HTML, CSS, JS).
• Browser renders (displays) the content.
Role of the Client and Server
• Client-side: Processing done in the browser. Languages: HTML, CSS, JavaScript, AngularJS,
React.
• Server-side: Processing done on the server. Languages: PHP, Python (Django/Flask), [Link],
Java.
Key Exam Point: Client-side scripting does NOT require a round trip to the server for
processing. It runs directly in the browser.
Static vs. Dynamic Web Pages
• Static Web Pages: Fixed content. Same page shown to every user. Written in plain HTML. No
database interaction. Example: a simple 'About Us' page.
• Dynamic Web Pages: Content changes based on user, time, or data. Uses server-side
scripting or JavaScript. Examples: Facebook feed, e-commerce product pages.
1.2 History of Scripting Technologies
HTML as a Foundation
HTML (HyperText Markup Language) is the backbone of web pages. It defines structure using tags like
<html>, <body>, <p>, <h1>, <a>, etc.
<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</body>
</html>
Early Use of Inline Scripting
JavaScript was introduced by Netscape in 1995. Early scripting was written inline inside HTML:
<button Me</button>
Inline scripting made pages interactive without server round-trips.
Limitations of Static HTML
• Cannot respond to user actions dynamically.
• Cannot fetch data without reloading the page.
• No real-time updates (e.g., live chat, notifications).
• Repetitive code; hard to maintain large pages.
JavaScript
JavaScript is a lightweight, interpreted scripting language that runs in the browser.
• Variables: var, let, const
• Data Types: Number, String, Boolean, Object, Array, Null, Undefined
• Functions: Regular functions and arrow functions
// Variables
var name = 'Alice';
let age = 20;
const PI = 3.14;
// Function
function greet(name) {
return 'Hello, ' + name;
}
// Arrow Function
const greet = (name) => 'Hello, ' + name;
// Array
let fruits = ['Apple', 'Mango', 'Banana'];
// Object
let student = { name: 'Alice', age: 20, city: 'Mumbai' };
1.3 Introduction to AJAX
AJAX Architecture
AJAX = Asynchronous JavaScript And XML. It allows web pages to communicate with the server and
update parts of the page WITHOUT reloading the whole page.
• Asynchronous: Requests are sent in the background; the user can still interact with the page.
• XML/JSON: Data format used for sending/receiving data (JSON is more popular today).
AJAX Actions (How AJAX Works)
• An event occurs in the browser (button click, page load, etc.).
• An XMLHttpRequest (XHR) object is created by JavaScript.
• The XHR object sends a request to the server.
• The server processes the request and sends back data.
• JavaScript reads the response and updates the page.
// Creating XMLHttpRequest
var xhttp = new XMLHttpRequest();
// Define what to do when response is received
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]('demo').innerHTML = [Link];
}
};
// Open and send request
[Link]('GET', '[Link]', true);
[Link]();
readyState values: 0=Unsent, 1=Opened, 2=Headers Received, 3=Loading, 4=Done. status
200 = OK.
1.4 Basics of JSON
JSON Objects
JSON = JavaScript Object Notation. A lightweight data-interchange format. Easy for humans to read
and for machines to parse.
• Syntax rules: Data is in key/value pairs. Keys must be strings in double quotes. Values can be
string, number, object, array, boolean, null.
// JSON Object
{
"name": "Alice",
"age": 20,
"isStudent": true,
"marks": [85, 90, 78],
"address": { "city": "Mumbai", "pin": "400001" }
}
JSON Scheme / Usage in JavaScript
// Converting JSON string to JS Object (Parsing)
var jsonStr = '{"name": "Alice", "age": 20}';
var obj = [Link](jsonStr);
[Link]([Link]); // Alice
// Converting JS Object to JSON string (Stringify)
var student = { name: 'Bob', age: 21 };
var jsonOutput = [Link](student);
[Link](jsonOutput); // {"name":"Bob","age":21}
// Accessing JSON data via AJAX
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
var data = [Link]([Link]);
[Link]('name').innerHTML = [Link];
}
};
1.5 Webpage with Python: Django and Flask Framework
Django Framework
Django is a high-level Python web framework that follows the MVT (Model-View-Template) pattern. It is
used for building full-featured web applications quickly.
• Model: Defines database structure.
• View: Contains business logic, processes requests.
• Template: HTML files with Django template language for displaying data.
# Simple Django View ([Link])
from [Link] import HttpResponse
def hello(request):
return HttpResponse('Hello, World!')
# URL mapping ([Link])
from [Link] import path
from . import views
urlpatterns = [
path('hello/', [Link], name='hello'),
]
Flask Framework
Flask is a micro web framework for Python. It is lightweight and minimal compared to Django. Suitable
for small to medium applications.
# Simple Flask App
from flask import Flask
app = Flask(__name__)
@[Link]('/')
def home():
return 'Hello from Flask!'
@[Link]('/user/<name>')
def user(name):
return f'Hello, {name}!'
if __name__ == '__main__':
[Link](debug=True)
Django vs Flask: Django is 'batteries-included' (admin panel, ORM, auth built-in). Flask is
minimal and flexible — you add only what you need.
Unit II: Angular Basics
2.1 Introduction to AngularJS
What is AngularJS?
AngularJS is a JavaScript-based open-source front-end framework maintained by Google. It extends
HTML with new attributes (directives) to make web pages dynamic and interactive.
AngularJS Extends HTML
AngularJS adds new attributes to HTML elements called directives. For example:
• ng-app: Defines the AngularJS application. Must be placed in the root element (usually <html>
or <body>).
• ng-model: Binds an input field to a variable.
• ng-bind: Binds a variable value to an HTML element.
• ng-controller: Attaches a controller to a section of the page.
<!DOCTYPE html>
<html>
<script
src='[Link]
</script>
<body ng-app=''>
<p>Enter Name: <input type='text' ng-model='name'></p>
<p>Hello, <span ng-bind='name'></span>!</p>
</body>
</html>
Expressions
AngularJS expressions are written inside double curly braces: {{ expression }}. They can contain
variables, operators, literals.
<!-- Expression examples -->
<p>{{ 5 + 3 }}</p> <!-- Output: 8 -->
<p>{{ 'Hello' + ' World' }}</p> <!-- Output: Hello World -->
<p>{{ firstName + ' ' + lastName }}</p>
MVC Architecture in AngularJS
• Model: The data of the application ($scope variables).
• View: The HTML template that displays the data.
• Controller: The JavaScript function that controls the data and behaviour.
In AngularJS, the Controller acts as the intermediary between Model and View. Changes in
the controller's $scope automatically update the View (two-way binding).
Application in AngularJS
An AngularJS application is defined by the ng-app directive. It can have a name to define a module:
// Define module
var app = [Link]('myApp', []);
// Define controller
[Link]('myCtrl', function($scope) {
$[Link] = 'Alice';
$[Link] = 20;
});
<!-- HTML -->
<div ng-app='myApp' ng-controller='myCtrl'>
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
</div>
Variables and Scope
$scope is the binding between the HTML (View) and the JavaScript (Controller). Variables defined on
$scope are accessible in the View.
[Link]('demoCtrl', function($scope) {
$[Link] = 'Welcome to AngularJS';
$[Link] = 0;
$[Link] = function() {
$[Link]++;
};
});
2.2 AngularJS Forms
FORM Tag
AngularJS uses the standard HTML <form> tag enhanced with ng- directives for validation and data
binding.
<form ng-app='myApp' ng-controller='formCtrl'>
<!-- Form content here -->
</form>
Form Fields
• Single-line text field: <input type='text' ng-model='username'>
• Password field: <input type='password' ng-model='pwd'>
• Multiple-line text area: <textarea ng-model='message'></textarea>
• Radio buttons: <input type='radio' ng-model='gender' value='Male'> Male
• Check boxes: <input type='checkbox' ng-model='agree'>
<form ng-app='myApp' ng-controller='formCtrl'>
Name: <input type='text' ng-model='[Link]'><br>
Password: <input type='password' ng-model='[Link]'><br>
Message: <textarea ng-model='[Link]'></textarea><br>
Gender:
<input type='radio' ng-model='[Link]' value='Male'> Male
<input type='radio' ng-model='[Link]' value='Female'> Female<br>
Agree: <input type='checkbox' ng-model='[Link]'><br>
<p>You entered: {{ user | json }}</p>
</form>
Pull Down Menus: SELECT and OPTION Tags
<!-- Static dropdown -->
<select ng-model='selectedCity'>
<option value='Mumbai'>Mumbai</option>
<option value='Pune'>Pune</option>
<option value='Delhi'>Delhi</option>
</select>
<p>Selected: {{ selectedCity }}</p>
<!-- Dynamic dropdown using ng-options -->
<select ng-model='selectedColor' ng-options='c for c in colors'></select>
// In Controller:
$[Link] = ['Red', 'Green', 'Blue'];
Buttons: submit, reset and generalized
<input type='submit' value='Submit'>
<input type='reset' value='Reset'>
<button ng-click='submitForm()'>Submit</button>
<button ng-click='resetForm()'>Reset</button>
Form Validation
AngularJS provides built-in form validation. Key properties:
• $valid: True if the form/field is valid.
• $invalid: True if the form/field is invalid.
• $dirty: True if the field has been modified.
• $pristine: True if the field has not been modified.
<form name='myForm' ng-app='myApp' novalidate>
<input type='text' name='uname' ng-model='[Link]'
required minlength='3'>
<span ng-show='[Link].$[Link]'>Name is required!</span>
<span ng-show='[Link].$[Link]'>Min 3 characters!</span>
<input type='email' name='email' ng-model='[Link]' required>
<span ng-show='[Link].$invalid && [Link].$dirty'>
Invalid email!
</span>
<button ng-disabled='myForm.$invalid'>Submit</button>
</form>
2.3 AngularJS Data Binding
Two-Way Binding
Two-way data binding means the View and the Model stay in sync automatically. When the model
changes, the view updates; when the view changes (user input), the model updates.
<div ng-app=''>
<input type='text' ng-model='message'>
<p>You typed: {{ message }}</p>
</div>
<!-- Typing in the input immediately updates the paragraph -->
ng-model Directive
ng-model is the core directive for two-way binding. It binds an input element to a $scope variable.
[Link]('bindCtrl', function($scope) {
$[Link] = 'Alice';
$[Link] = 'Smith';
});
<!-- HTML -->
<input ng-model='firstName'>
<input ng-model='lastName'>
<p>Full Name: {{ firstName + ' ' + lastName }}</p>
2.4 Filters
Built-In Filters
• uppercase: {{ 'hello' | uppercase }} → HELLO
• lowercase: {{ 'HELLO' | lowercase }} → hello
• currency: {{ 1200 | currency }} → $1,200.00
• number: {{ 3.14159 | number:2 }} → 3.14
• date: {{ today | date:'dd-MM-yyyy' }} → 10-04-2026
• orderBy: Sorts an array.
• filter: Filters an array based on a condition.
• limitTo: Limits array/string to a given number of items/chars.
<!-- Using filters in HTML -->
<p>{{ 'hello world' | uppercase }}</p>
<p>{{ price | currency:'Rs.' }}</p>
<p>{{ today | date:'fullDate' }}</p>
<!-- filter on a list -->
<ul>
<li ng-repeat='name in names | filter:searchText | orderBy'>{{ name
}}</li>
</ul>
<input ng-model='searchText' placeholder='Search...'>
Custom Filter
[Link]('reverse', function() {
return function(input) {
return [Link]('').reverse().join('');
};
});
<!-- Usage -->
<p>{{ 'hello' | reverse }}</p> <!-- olleh -->
Chaining Multiple Filters
<!-- Chaining: first reverse, then uppercase -->
<p>{{ 'hello' | reverse | uppercase }}</p> <!-- OLLEH -->
2.5 AngularJS Events
AngularJS provides directives for handling DOM events:
• ng-click: Fires when element is clicked.
• ng-mousedown: Fires when mouse button is pressed.
• ng-mouseup: Fires when mouse button is released.
• ng-mouseover: Fires when mouse hovers over element.
• ng-change: Fires when input value changes.
<div ng-app='myApp' ng-controller='eventCtrl'>
<button ng-click='clickCount = clickCount + 1'>
Clicked {{ clickCount }} times
</button>
<div ng-mousedown='status="Mouse Down"'
ng-mouseup='status="Mouse Up"'>
Mouse Event Area
</div>
<p>Status: {{ status }}</p>
</div>
[Link]('eventCtrl', function($scope) {
$[Link] = 0;
$[Link] = 'No event yet';
});
Unit III: Working with AngularJS
3.1 AngularJS Tables
Display Data in a Table
[Link]('tableCtrl', function($scope) {
$[Link] = [
{ name: 'Alice', marks: 88, grade: 'A' },
{ name: 'Bob', marks: 74, grade: 'B' },
{ name: 'Carol', marks: 92, grade: 'A+' }
];
});
<table ng-app='myApp' ng-controller='tableCtrl' border='1'>
<tr><th>Name</th><th>Marks</th><th>Grade</th></tr>
<tr ng-repeat='s in students'>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</table>
Adding Style to Table Data
<!-- Conditional styling with ng-class -->
<tr ng-repeat='s in students' ng-class='{highlight: [Link] > 85}'>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
<style>
.highlight { background-color: lightgreen; }
</style>
orderBy Filter in Tables
<!-- Sort by marks ascending -->
<tr ng-repeat='s in students | orderBy:"marks"'>
<!-- Sort by marks descending -->
<tr ng-repeat='s in students | orderBy:"-marks"'>
<!-- Sort by name -->
<tr ng-repeat='s in students | orderBy:"name"'>
uppercase Filter in Tables
<td>{{ [Link] | uppercase }}</td>
Table Index: $index, $even, $odd
• $index: The current index (0-based) of the repeated item.
• $even: True when $index is even (0, 2, 4...).
• $odd: True when $index is odd (1, 3, 5...).
<tr ng-repeat='s in students'
ng-class='{evenRow: $even, oddRow: $odd}'>
<td>{{ $index + 1 }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
<style>
.evenRow { background-color: #f2f2f2; }
.oddRow { background-color: #ffffff; }
</style>
3.2 AngularJS Controllers
Initializing the Model with Controllers
Controllers initialize the $scope (model) with default values and define functions.
var app = [Link]('myApp', []);
[Link]('initCtrl', function($scope) {
// Initialize model
$[Link] = 'Student Portal';
$[Link] = 45;
$[Link] = ['Math', 'Science', 'English'];
});
Role of a Controller
• Initializes data on the $scope.
• Defines functions (methods) that can be called from the View.
• Acts as the bridge between the Model and the View.
• Does NOT manipulate the DOM directly (that's the View's job).
Controllers & Modules
// A module can have multiple controllers
var app = [Link]('schoolApp', []);
[Link]('studentCtrl', function($scope) {
$[Link] = ['Alice', 'Bob', 'Carol'];
});
[Link]('teacherCtrl', function($scope) {
$[Link] = ['Mr. Smith', 'Ms. Jones'];
});
Controller Business Logic
[Link]('calcCtrl', function($scope) {
$scope.num1 = 0;
$scope.num2 = 0;
$[Link] = 0;
$[Link] = function() {
$[Link] = $scope.num1 + $scope.num2;
};
$[Link] = function() {
$[Link] = $scope.num1 * $scope.num2;
};
});
Presentation Logic and Formatting Data
[Link]('formatCtrl', function($scope) {
$[Link] = 55000;
$[Link] = new Date('2000-05-15');
$[Link] = function(first, last) {
return [Link]() + ' ' + [Link]();
};
});
<!-- In HTML -->
<p>Salary: {{ salary | currency:'Rs.' }}</p>
<p>DOB: {{ dob | date:'dd MMM yyyy' }}</p>
<p>Name: {{ getFullName('alice', 'smith') }}</p>
3.3 Attaching Properties and Functions to Scope
[Link]('scopeCtrl', function($scope) {
// Attaching property
$[Link] = 'Hello!';
// Attaching a function
$[Link] = function() {
alert($[Link]);
};
// Attaching an object
$[Link] = {
name: 'Alice',
age: 20
};
// Attaching an array
$[Link] = ['Item1', 'Item2', 'Item3'];
});
3.4 Nested Controllers
Controllers can be nested. The inner controller inherits the outer controller's $scope via prototypal
inheritance.
<div ng-app='myApp'>
<div ng-controller='outerCtrl'>
<p>Outer: {{ outerMsg }}</p>
<div ng-controller='innerCtrl'>
<p>Inner: {{ innerMsg }}</p>
<p>Also Outer (inherited): {{ outerMsg }}</p>
</div>
</div>
</div>
[Link]('outerCtrl', function($scope) {
$[Link] = 'I am outer!';
});
[Link]('innerCtrl', function($scope) {
$[Link] = 'I am inner!';
});
Using Filters in Controllers
// Inject $filter service
[Link]('filterCtrl', function($scope, $filter) {
$[Link] = 1500;
$[Link] = $filter('currency')($[Link], 'Rs.');
$[Link] = 'alice';
$[Link] = $filter('uppercase')($[Link]);
});
3.5 Controllers in External Files
It is good practice to separate JavaScript (controllers) from HTML.
<!-- [Link] -->
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<script src='[Link]'></script>
<script src='[Link]'></script>
<script src='controllers/[Link]'></script>
</head>
<body>
<div ng-controller='studentCtrl'>
<p>{{ message }}</p>
</div>
</body>
</html>
// [Link]
var app = [Link]('myApp', []);
// controllers/[Link]
[Link]('studentCtrl', function($scope) {
$[Link] = 'Hello from external controller!';
$[Link] = ['Alice', 'Bob', 'Carol'];
});
Unit IV: Introduction to React Framework
4.1 Introduction to React Framework
What is React?
React is an open-source JavaScript library for building user interfaces, developed by Facebook (Meta).
It is used for building fast, interactive, component-based Single Page Applications (SPAs).
Key Features of React
• Component-Based: UI is broken into reusable, independent components.
• Virtual DOM: React uses a Virtual DOM for faster UI updates. It compares the new virtual DOM
with the old one (diffing) and updates only the changed parts.
• One-Way Data Flow: Data flows from parent to child via props (unlike AngularJS two-way
binding).
• JSX: JavaScript XML — allows writing HTML-like syntax inside JavaScript.
• Reusable Components: Once created, components can be used anywhere.
• React Hooks: Functions that let functional components use state and lifecycle features.
React Architecture
React follows a component tree architecture. The root component (App) renders child components,
each managing its own state and UI.
// Basic React App structure
// [Link] — Entry point
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = [Link]([Link]('root'));
[Link](<App />);
JSX — JavaScript XML
// JSX allows HTML-like syntax in JavaScript
const element = <h1>Hello, World!</h1>;
// JSX expressions
const name = 'Alice';
const greeting = <p>Hello, {name}!</p>;
// JSX Rules:
// 1. Return only ONE root element (wrap in <div> or <>...</>)
// 2. Use className instead of class
// 3. Self-close empty tags: <img />, <br />
// 4. JavaScript expressions in { }
4.2 Components
Functional Components
Functional components are plain JavaScript functions that return JSX. They are the modern, preferred
way to write React components.
// Basic Functional Component
function Welcome() {
return <h1>Welcome to React!</h1>;
}
// Arrow function component
const Greeting = () => {
return (
<div>
<h2>Hello!</h2>
<p>This is a functional component.</p>
</div>
);
};
export default Greeting;
Class Components
Class components are older React components that extend [Link]. They use render() to
return JSX and use [Link] for state management.
import React, { Component } from 'react';
class Welcome extends Component {
constructor(props) {
super(props);
[Link] = { message: 'Hello from Class Component!' };
}
render() {
return (
<div>
<h1>{[Link]}</h1>
<p>Name: {[Link]}</p>
</div>
);
}
}
export default Welcome;
Passing and Using Props
Props (properties) are used to pass data from a parent component to a child component. Props are
read-only.
// Child Component
function StudentCard(props) {
return (
<div>
<h3>{[Link]}</h3>
<p>Roll No: {[Link]}</p>
<p>Marks: {[Link]}</p>
</div>
);
}
// Parent Component
function App() {
return (
<div>
<StudentCard name='Alice' rollNo={1} marks={88} />
<StudentCard name='Bob' rollNo={2} marks={74} />
</div>
);
}
Props flow ONE WAY: from parent to child. A child cannot modify its props. Use state (in
parent) and callback functions to allow child-to-parent communication.
4.3 Lifecycle — Mounting, Updating and Unmounting
React components go through a lifecycle. Class components have explicit lifecycle methods; functional
components use the useEffect hook.
Mounting (Component added to DOM)
• constructor(): Called first; initialize state.
• render(): Returns JSX to display.
• componentDidMount(): Called after component is rendered. Good for API calls, subscriptions.
Updating (State or Props change)
• render(): Called again to re-render.
• componentDidUpdate(prevProps, prevState): Called after update. Compare prev and current
to decide if side effects are needed.
Unmounting (Component removed from DOM)
• componentWillUnmount(): Cleanup (clear timers, cancel API calls, remove subscriptions).
class LifecycleDemo extends Component {
constructor(props) {
super(props);
[Link] = { count: 0 };
[Link]('1. Constructor');
}
componentDidMount() {
[Link]('3. componentDidMount — component is on screen');
// Good place to fetch data from API
}
componentDidUpdate(prevProps, prevState) {
if ([Link] !== [Link]) {
[Link]('4. componentDidUpdate — count changed');
}
}
componentWillUnmount() {
[Link]('5. componentWillUnmount — cleanup here');
}
render() {
[Link]('2. render');
return (
<div>
<p>Count: {[Link]}</p>
<button => [Link]({ count: [Link] +
1 })}>
Increment
</button>
</div>
);
}
}
4.4 React Hooks
useState
useState is a Hook that lets functional components manage state.
import React, { useState } from 'react';
function Counter() {
// [currentValue, setterFunction] = useState(initialValue)
const [count, setCount] = useState(0);
const [name, setName] = useState('Alice');
return (
<div>
<p>Count: {count}</p>
<button => setCount(count + 1)}>Increment</button>
<button => setCount(count - 1)}>Decrement</button>
<button => setCount(0)}>Reset</button>
<input value={name} => setName([Link])} />
<p>Hello, {name}!</p>
</div>
);
}
useEffect
useEffect lets functional components perform side effects: data fetching, subscriptions, timers, DOM
manipulation.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
// Runs after every render (no dependency array)
useEffect(() => {
[Link]('Component rendered');
});
// Runs only on mount (empty dependency array [])
useEffect(() => {
[Link]('Component mounted — runs once');
const timer = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
// Cleanup on unmount
return () => clearInterval(timer);
}, []);
// Runs when 'seconds' changes
useEffect(() => {
[Link] = `Timer: ${seconds}s`;
}, [seconds]);
return <p>Seconds: {seconds}</p>;
}
useEffect dependency array: [] = run once on mount; [var] = run when var changes; no array
= run after every render.
useContext
useContext allows functional components to consume a React Context without prop-drilling.
import React, { createContext, useContext, useState } from 'react';
// 1. Create context
const ThemeContext = createContext('light');
// 2. Provider component
function App() {
const [theme, setTheme] = useState('light');
return (
<[Link] value={theme}>
<Toolbar />
<button => setTheme(theme === 'light' ? 'dark' :
'light')}>
Toggle Theme
</button>
</[Link]>
);
}
// 3. Consumer component (any level deep)
function Toolbar() {
const theme = useContext(ThemeContext);
return <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>
Current theme: {theme}
</div>;
}
Unit V: Working with React Framework
5.1 Event Handling
Binding Event Handlers
React uses camelCase event names (onClick, onChange, onSubmit) and passes functions as event
handlers.
// Inline handler
<button => alert('Clicked!')}>Click Me</button>
// Separate function handler
function ButtonDemo() {
const handleClick = () => {
alert('Button was clicked!');
};
return <button Me</button>;
}
// Passing parameters to handler
<button => handleClick('Alice')}>Greet Alice</button>
Arrow Functions vs. Regular Functions
• Arrow Function: Does not have its own 'this'. Inherits 'this' from surrounding scope. Shorter
syntax. Preferred in React for event handlers.
• Regular Function: Has its own 'this'. Must be explicitly bound (e.g., in class components:
[Link] = [Link](this) in constructor).
// Arrow function — no binding needed
class Demo extends [Link] {
handleClick = () => {
[Link](this); // refers to component instance
}
render() {
return <button > }
}
// Regular function — needs binding
class Demo extends [Link] {
constructor(props) {
super(props);
[Link] = [Link](this);
}
handleClick() {
[Link](this);
}
render() {
return <button > }
}
5.2 Working with Forms
Adding Components and Handling Forms
import React, { useState } from 'react';
function LoginForm() {
const [formData, setFormData] = useState({
username: '',
password: ''
});
const handleChange = (e) => {
setFormData({ ...formData, [[Link]]: [Link] });
};
return (
<div>
<input
type='text'
name='username'
value={[Link]}
> placeholder='Username'
/>
<input
type='password'
name='password'
value={[Link]}
> placeholder='Password'
/>
</div>
);
}
Submitting Forms
function ContactForm() {
const [data, setData] = useState({ name: '', email: '', message: '' });
const [submitted, setSubmitted] = useState(false);
const handleChange = (e) => {
setData({ ...data, [[Link]]: [Link] });
};
const handleSubmit = (e) => {
[Link](); // Prevent page reload
[Link]('Submitted:', data);
setSubmitted(true);
};
if (submitted) return <p>Thank you, {[Link]}!</p>;
return (
<form > <input name='name' value={[Link]} > placeholder='Name' />
<input name='email' value={[Link]} > placeholder='Email' type='email' />
<textarea name='message' value={[Link]}
> <button type='submit'>Submit</button>
</form>
);
}
Form Validation in React
function ValidatedForm() {
const [name, setName] = useState('');
const [errors, setErrors] = useState({});
const validate = () => {
let errs = {};
if (!name) [Link] = 'Name is required';
else if ([Link] < 3) [Link] = 'Min 3 characters required';
return errs;
};
const handleSubmit = (e) => {
[Link]();
const errs = validate();
if ([Link](errs).length === 0) {
alert('Form submitted successfully!');
} else {
setErrors(errs);
}
};
return (
<form > <input value={name} => setName([Link])} />
{[Link] && <span style={{color:'red'}}>{[Link]}</span>}
<button type='submit'>Submit</button>
</form>
);
}
5.3 Lists and Keys
Rendering Lists
Use the JavaScript .map() method to render arrays as lists in React.
function FruitList() {
const fruits = ['Apple', 'Mango', 'Banana', 'Orange'];
return (
<ul>
{[Link]((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
List with Key
Keys help React identify which items have changed, been added, or removed. Keys must be unique
among siblings.
function StudentList() {
const students = [
{ id: 1, name: 'Alice', marks: 88 },
{ id: 2, name: 'Bob', marks: 74 },
{ id: 3, name: 'Carol', marks: 92 },
];
return (
<table>
<thead><tr><th>Name</th><th>Marks</th></tr></thead>
<tbody>
{[Link](student => (
<tr key={[Link]}>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>
))}
</tbody>
</table>
);
}
IMPORTANT: Always use a unique, stable key (like database ID). Avoid using array index
as key when list items can be reordered or deleted — it causes bugs.
Using map() to Render Lists of Elements
// Rendering components with map()
function ProductCard({ name, price }) {
return <div><h3>{name}</h3><p>Rs. {price}</p></div>;
}
function ProductList() {
const products = [
{ id: 101, name: 'Laptop', price: 45000 },
{ id: 102, name: 'Phone', price: 15000 },
{ id: 103, name: 'Tablet', price: 25000 },
];
return (
<div>
{[Link](p => (
<ProductCard key={[Link]} name={[Link]} price={[Link]} />
))}
</div>
);
}
5.4 Cascading Style Sheets (CSS) in React
Different Types of Style Sheets
• External CSS: A separate .css file imported into the component.
• Internal CSS (CSS Modules): Scoped CSS per component using [Link].
• Inline CSS: Style applied directly as a JavaScript object in JSX.
• CSS-in-JS: Libraries like styled-components that let you write CSS inside JavaScript files.
// 1. External CSS — import in component
import './[Link]';
function App() {
return <div className='container'><h1 className='title'>Hello</h1></div>;
}
/* [Link] */
.container { padding: 20px; }
.title { color: blue; font-size: 24px; }
// 2. CSS Modules (scoped styles — no conflicts)
import styles from './[Link]';
function Button() {
return <button className={[Link]}>Click Me</button>;
}
/* [Link] */
.btn { background: blue; color: white; padding: 10px 20px; border-radius:
5px; }
// 3. Inline CSS in JSX
function InlineStyleDemo() {
const headingStyle = {
color: 'red',
fontSize: '28px',
fontWeight: 'bold',
textAlign: 'center'
};
return (
<div>
<h1 style={headingStyle}>Styled Heading</h1>
<p style={{ color: 'green', marginTop: '10px' }}>Inline para</p>
</div>
);
}
// Note: CSS properties use camelCase in JSX:
// font-size → fontSize
// background-color → backgroundColor
// border-radius → borderRadius
Styling Libraries
• Bootstrap: CSS framework with pre-built classes for layout, buttons, forms, etc.
• Material-UI (MUI): React component library based on Google's Material Design.
• Tailwind CSS: Utility-first CSS framework with small utility classes.
Popular CSS Frameworks: Bootstrap in React
// Install Bootstrap
// npm install bootstrap
// Import in [Link] or [Link]
import 'bootstrap/dist/css/[Link]';
// Use Bootstrap classes in JSX
function BootstrapDemo() {
return (
<div className='container mt-4'>
<h1 className='text-primary'>Bootstrap in React</h1>
<button className='btn btn-success me-2'>Success</button>
<button className='btn btn-danger'>Danger</button>
<div className='alert alert-warning mt-3'>
This is a warning alert!
</div>
</div>
);
}
Material-UI (MUI) in React
// Install: npm install @mui/material @emotion/react @emotion/styled
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Alert from '@mui/material/Alert';
function MUIDemo() {
return (
<div>
<Button variant='contained' color='primary'>Primary</Button>
<Button variant='outlined' color='secondary'>Secondary</Button>
<TextField label='Enter Name' variant='outlined' />
<Alert severity='success'>This is a success alert!</Alert>
</div>
);
}
End of Notes — All 5 Units Covered
Study Tip: Practice all code examples in a browser or editor. Focus on syntax differences between
AngularJS and React.