VIVEKANANDA GLOBAL UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE AND APPLICATIONS
LECTURE NOTES
WEBSITE DESIGN AND DEVELOPMENT
UGCSA104
MODULE – 2
Building dynamic user interfaces with
Name of the Module
REACT
• Understanding React components, props, and
state
• Creating reusable UI components in React
• React component lifecycle methods
• Handling user input with forms and events in
Module Content React
• Styling React components using CSS and CSS-in-
JS libraries
• Project: Developing a dynamic user interface
for a web application using React
Name of HOD Mr. RAKESH SHARMA
Name of Lecturer Mr. NITIN MATHEW VARGHESE
UNDERSTANDING REACT COMPONENTS, PROPS, AND STATE
1. Introduction to React
• React is a JavaScript library for building user interfaces.
• It follows a component-based architecture, where UI is divided into small, reusable
pieces called components.
• Components interact with each other using props and manage their internal data
using state.
2. React Components
Definition:
• A component is a reusable piece of UI in React.
• Components are the building blocks of a React application.
Types of Components:
1. Functional Components
o Simple JavaScript functions that return JSX (JavaScript XML).
o Preferred in modern React (especially with Hooks).
o Example:
function Greeting() {
return <h1>Hello, World!</h1>;
}
2. Class Components
o ES6 classes that extend [Link].
o Contain lifecycle methods and a render() function.
o Example:
class Greeting extends [Link] {
render() {
return <h1>Hello, World!</h1>;
}
}
Key Points:
• Components must start with a capital letter (e.g., Greeting not greeting).
• Can be reused multiple times within the app.
• Components can be nested (a component inside another).
3. Props (Properties)
Definition:
• Props are inputs to a component.
• They are read-only (immutable inside the child component).
• Props allow data sharing between components (parent → child).
Example:
function Welcome(props) {
return <h1>Hello, {[Link]}!</h1>;
}
// Usage
<Welcome name="Alice" />
<Welcome name="Bob" />
Key Points:
• Passed like attributes in HTML.
• Cannot be modified by the child component.
• Enable component reusability by providing dynamic values.
4. State
Definition:
• State is an object that stores a component’s mutable data.
• Unlike props, state is managed inside the component and can change over time.
• When state changes, the component re-renders automatically.
Example (using Hooks in Functional Component):
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click Me
</button>
</div>
);
}
Key Points:
• Initialization: State is usually initialized in the constructor (class) or using useState()
(function).
• Updates: State updates are asynchronous in React.
• Re-rendering: Any change in state triggers UI updates.
5. Difference Between Props and State
Feature Props State
Definition Inputs passed from parent to child Data managed inside the component
Immutable (cannot be changed by
Mutability Mutable (can be updated)
child)
Usage For passing static or dynamic data For interactive, dynamic data
Responsibility Controlled by parent component Controlled by the component itself
Example <Welcome name="Alice" /> useState(0) for counter
6. How Components, Props, and State Work Together
• Components are the UI building blocks.
• Props provide external data to components.
• State manages internal, changing data.
• Together, they create dynamic, reusable, and interactive UIs.
Example:
function UserProfile(props) {
const [followers, setFollowers] = useState([Link]);
return (
<div>
<h2>{[Link]}</h2>
<p>Followers: {followers}</p>
<button onClick={() => setFollowers(followers + 1)}>
Follow
</button>
</div>
);
}
// Usage
<UserProfile name="Alice" initialFollowers={100} />
7. Summary
• Components: Reusable UI blocks (functional or class-based).
• Props: Read-only inputs passed from parent → child.
• State: Internal data that can change over time, causing re-renders.
• Together, they make React applications modular, dynamic, and interactive.
CREATING REUSABLE UI COMPONENTS IN REACT
1. Introduction
• In modern web applications, reusability is a key principle.
• Instead of writing the same UI code multiple times, React encourages building
reusable components.
• A reusable UI component is a self-contained piece of code that can be used in
multiple places with different data.
Example of reusable UI component: Buttons, form inputs, modals, navigation bars, cards,
etc.
2. What Makes a Component Reusable?
A reusable component should:
1. Be independent – Not tightly coupled with a specific parent or page.
2. Use props effectively – Accept external data to make it flexible.
3. Be configurable – Support variations (size, style, behavior).
4. Avoid hardcoding – Should not rely on fixed text or values.
5. Follow single responsibility principle – Each component does one job well.
3. Steps to Create Reusable UI Components
Step 1: Identify Common UI Patterns
• Look for repeating UI elements (e.g., buttons, input fields, cards).
• Extract them into separate components.
Step 2: Use Functional Components
• Modern React prefers functional components with Hooks.
• Keep the component small and focused.
Step 3: Pass Data Using Props
• Make the component dynamic by passing values via props.
• Example: A Button component can take label, color, onClick as props.
Step 4: Use Composition
• Instead of making huge, rigid components, use composition (nesting components) to
build flexible UI.
Step 5: Style for Reusability
• Use CSS modules, styled-components, or Tailwind CSS for customizable styling.
• Provide options for themes or variants.
4. Example: Reusable Button Component
// Reusable Button Component
function Button({ label, onClick, type = "primary" }) {
const styles = {
primary: { backgroundColor: "blue", color: "white", padding: "10px 20px" },
secondary: { backgroundColor: "gray", color: "black", padding: "10px 20px" }
};
return (
<button style={styles[type]} onClick={onClick}>
{label}
</button>
);
}
// Usage
<Button label="Save" type="primary" onClick={() => alert("Saved!")} />
<Button label="Cancel" type="secondary" onClick={() => alert("Cancelled!")} />
Why reusable?
• The same Button can be used in different places with different labels, styles, and
actions.
5. Example: Reusable Card Component
function Card({ title, description, children }) {
return (
<div style={{ border: "1px solid #ccc", padding: "15px", borderRadius: "8px" }}>
<h3>{title}</h3>
<p>{description}</p>
{children} {/* Composition for flexibility */}
</div>
);
}
// Usage
<Card title="React" description="A JavaScript library for building UI">
<Button label="Learn More" type="primary" />
</Card>
Why reusable?
• The same Card can be used for different data and actions.
• Composition allows injecting other components inside the Card.
6. Benefits of Reusable Components
1. Consistency – UI looks uniform across the application.
2. Maintainability – Bug fixes or updates need to be done only once.
3. Faster development – Saves time by avoiding duplicate code.
4. Scalability – Easier to extend application by combining existing components.
5. Readability – Code becomes cleaner and easier to understand.
7. Best Practices
• Keep components small and focused (single responsibility).
• Use props and default props for customization.
• Avoid duplication – If code repeats, extract it.
• Name components clearly (e.g., Button, UserCard, Navbar).
• Document the props – Helps when reusing the component later.
• Use prop-types or TypeScript for type-checking props.
• Leverage composition over complex configuration (children make components
flexible).
REACT COMPONENT LIFECYCLE METHODS
1. Introduction
• In React, every component goes through a series of phases from creation to
destruction.
• These phases are collectively known as the component lifecycle.
• Lifecycle methods are special methods in class-based components that allow
developers to run code at specific points in a component’s life.
• Although modern React encourages functional components with Hooks, lifecycle
methods remain important for understanding React’s working.
2. Lifecycle Phases
A React component’s lifecycle has three main phases:
1. Mounting – When the component is created and inserted into the DOM.
2. Updating – When the component’s state or props change, causing a re-render.
3. Unmounting – When the component is removed from the DOM.
3. Lifecycle Methods in Each Phase
A) Mounting Phase
Happens when a component is created and added to the DOM.
Key methods:
1. constructor(props)
o Called before the component is mounted.
o Used for initializing state and binding methods.
constructor(props) {
super(props);
[Link] = { count: 0 };
}
2. static getDerivedStateFromProps(props, state)
o Rarely used.
o Updates state based on changes in props before rendering.
3. render()
o Required method.
o Returns JSX to display the UI.
4. componentDidMount()
o Called once after the component is rendered into the DOM.
o Used for API calls, DOM manipulations, or starting timers.
componentDidMount() {
[Link]("Component mounted!");
}
B) Updating Phase
Triggered when props or state change, leading to re-render.
Key methods:
1. static getDerivedStateFromProps(props, state)
o Same as in mounting, called before every re-render.
2. shouldComponentUpdate(nextProps, nextState)
o Returns true or false.
o Used for performance optimization (prevents unnecessary re-render).
3. render()
o Re-renders the UI with updated data.
4. getSnapshotBeforeUpdate(prevProps, prevState)
o Captures information (e.g., scroll position) before DOM updates.
5. componentDidUpdate(prevProps, prevState, snapshot)
o Runs after re-render.
o Good for fetching new data if props/state change.
componentDidUpdate(prevProps, prevState) {
if ([Link] !== [Link]) {
[Link]("Count updated!");
}
}
C) Unmounting Phase
Happens when a component is removed from the DOM.
Key method:
1. componentWillUnmount()
o Called just before a component is destroyed.
o Used to clean up (stop timers, cancel API calls, remove event listeners).
componentWillUnmount() {
[Link]("Component will be removed!");
}
4. Lifecycle Diagram (Simplified)
MOUNTING → Updating → UNMOUNTING
Mounting:
constructor() → getDerivedStateFromProps() → render() → componentDidMount()
Updating:
getDerivedStateFromProps() → shouldComponentUpdate() → render() →
getSnapshotBeforeUpdate() → componentDidUpdate()
Unmounting:
componentWillUnmount()
5. Example of Lifecycle Methods
import React from "react";
class LifecycleDemo extends [Link] {
constructor(props) {
super(props);
[Link] = { count: 0 };
[Link]("Constructor");
}
componentDidMount() {
[Link]("Component Mounted");
}
shouldComponentUpdate(nextProps, nextState) {
[Link]("Should Component Update");
return true;
}
componentDidUpdate(prevProps, prevState) {
[Link]("Component Updated");
}
componentWillUnmount() {
[Link]("Component Will Unmount");
}
render() {
[Link]("Render");
return (
<div>
<p>Count: {[Link]}</p>
<button onClick={() => [Link]({ count: [Link] + 1 })}>
Increment
</button>
</div>
);
}
}
6. Lifecycle Methods in Functional Components
• Functional components don’t have lifecycle methods.
• Instead, React provides the useEffect Hook to mimic lifecycle behavior:
import React, { useState, useEffect } from "react";
function LifecycleHookDemo() {
const [count, setCount] = useState(0);
// componentDidMount + componentDidUpdate
useEffect(() => {
[Link]("Component Mounted or Updated");
return () => {
[Link]("Component Will Unmount"); // cleanup
};
}, [count]); // runs when 'count' changes
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
HANDLING USER INPUT WITH FORMS AND EVENTS IN REACT
1. Introduction
• Forms are essential in web applications for collecting user input (e.g., login,
registration, search).
• In plain HTML, form inputs maintain their own state, but in React, input values are
usually controlled by state.
• React uses a concept called controlled components and provides a powerful way to
handle events (like clicks, typing, submitting forms).
2. Forms in React
Traditional HTML Form:
<form>
<input type="text" name="username" />
<button type="submit">Submit</button>
</form>
Problem in React:
• React manages UI via its virtual DOM and state.
• Directly letting the browser control form input values makes it hard to synchronize
input values with React’s state.
3. Controlled Components
• A controlled component is a form element (input, textarea, select) whose value is
controlled by React state.
• The input value is set via state, and any change updates the state.
Example: Controlled Input
import React, { useState } from "react";
function FormExample() {
const [name, setName] = useState("");
const handleChange = (event) => {
setName([Link]); // update state
};
const handleSubmit = (event) => {
[Link](); // prevent page reload
alert(`Hello, ${name}!`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);}
Key points:
• value attribute is tied to React state.
• onChange updates state whenever the user types.
• This keeps React’s state and form input always in sync.
4. Uncontrolled Components
• In an uncontrolled component, the form input value is handled by the DOM, not
React.
• Accessed using refs (reference to DOM element).
• Useful for quick forms but less recommended in large apps.
Example: Uncontrolled Input
import React, { useRef } from "react";
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (event) => {
[Link]();
alert(`Hello, ${[Link]}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
5. Handling Events in React
Event Handling Basics
• React events are named using camelCase (onClick, onChange, onSubmit).
• In JSX, event handlers are passed as functions, not strings (unlike HTML).
Example: Button Click Event
function ClickButton() {
const handleClick = () => {
alert("Button clicked!");
};
return <button onClick={handleClick}>Click Me</button>;
}
6. Common Form Events in React
Event Triggered When… Example Usage
onChange User types/selects input Update state on typing
onSubmit Form is submitted Prevent reload, process data
onClick Button clicked Submit form, trigger action
onFocus Input gets focus Highlight field
onBlur Input loses focus Validate input
onKeyDown Key pressed Detect shortcuts
7. Handling Multiple Inputs
Instead of writing separate handlers for each field, use a single handler for multiple inputs.
Example: Multiple Inputs with One Handler
function MultiInputForm() {
const [formData, setFormData] = [Link]({
username: "",
email: ""
});
const handleChange = (event) => {
const { name, value } = [Link];
setFormData({ ...formData, [name]: value }); // update corresponding field
};
const handleSubmit = (event) => {
[Link]();
alert(`User: ${[Link]}, Email: ${[Link]}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={[Link]}
onChange={handleChange}
/>
<input
type="email"
name="email"
value={[Link]}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
8. Form Validation
• Validation can be done inline or using libraries like Formik or React Hook Form.
Simple Inline Validation Example
function ValidatedForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e) => {
[Link]();
if () {
setError("Invalid email!");
} else {
setError("");
alert("Form submitted!");
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail([Link])}
/>
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
9. Best Practices
• Prefer controlled components for predictability and easier validation.
• Use a single state object for multiple inputs in large forms.
• Always call [Link]() to stop page reload on form submit.
• Use form libraries (Formik, React Hook Form) for complex forms.
• Keep event handlers separate from JSX for readability.
• Validate inputs before submission to improve UX.
10. Summary
• React handles user input through controlled and uncontrolled components.
• Controlled components (recommended) use React state to manage input values.
• Events like onChange, onSubmit, and onClick allow dynamic interaction with forms.
• Handling multiple inputs and validation is crucial for building real-world apps.
• Best practices include centralizing form state, preventing default submit behavior,
and using libraries for advanced forms.
STYLING REACT COMPONENTS USING CSS AND CSS-IN-JS LIBRARIES
1. Introduction
• In React, styling is a crucial part of building modern, user-friendly interfaces.
• React offers multiple approaches to style components:
1. Traditional CSS (separate .css files)
2. CSS Modules (scoped styles)
3. Inline Styling (using the style attribute in JSX)
4. CSS-in-JS libraries (e.g., Styled Components, Emotion)
Each approach has its strengths, and the choice depends on the project requirements.
2. Styling React Components with CSS
A) Traditional CSS
• Import .css files into React components.
• Styles are global, meaning class names may conflict across components.
Example:
/* [Link] */
.title {
color: blue;
font-size: 24px;
}
// [Link]
import "./[Link]";
function App() {
return <h1 className="title">Hello, React!</h1>;
}
Pros: Simple, easy for small projects.
Cons: No built-in scoping; naming collisions possible.
B) CSS Modules
• A way to scope styles locally to a component.
• Class names are converted into unique identifiers automatically.
Example:
/* [Link] */
.button {
background-color: blue;
color: white;
padding: 10px;
}
// [Link]
import styles from "./[Link]";
function Button() {
return <button className={[Link]}>Click Me</button>;
}
Pros: Prevents naming conflicts, modular.
Cons: Slightly more setup, class management needed.
C) Inline Styling
• Define styles as JavaScript objects and apply them with the style attribute.
• React automatically adds vendor prefixes where necessary.
Example:
function InlineStyleExample() {
const buttonStyle = {
backgroundColor: "green",
color: "white",
padding: "10px"
};
return <button style={buttonStyle}>Submit</button>;
}
Pros: Dynamic styles (computed in JS).
Cons: No pseudo-classes (:hover) or media queries directly.
3. CSS-in-JS Libraries
CSS-in-JS is a styling technique where CSS is written inside JavaScript files.
Popular libraries: Styled Components, Emotion, JSS.
A) Styled Components
• Uses tagged template literals to define styles.
• Styles are scoped to components automatically.
• Supports dynamic props and theming.
Example:
import styled from "styled-components";
const Button = [Link]`
background: ${(props) => ([Link] ? "blue" : "gray")};
color: white;
padding: 10px 20px;
border-radius: 5px;
`;
function App() {
return (
<>
<Button primary>Primary Button</Button>
<Button>Default Button</Button>
</>
);
}
Pros: Scoped styles, dynamic theming, cleaner syntax.
Cons: Larger bundle size, learning curve.
B) Emotion
• Similar to Styled Components but more lightweight.
• Supports CSS prop and styled API.
Example:
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
const buttonStyle = css`
background: purple;
color: white;
padding: 10px;
`;
function App() {
return <button css={buttonStyle}>Click Me</button>;
}
Pros: Flexible, integrates well with existing CSS.
Cons: Requires Babel setup for advanced usage.
C) JSS (CSS as JS objects)
• Styles are written as JavaScript objects and applied using hooks or HOCs.
Example:
import { createUseStyles } from "react-jss";
const useStyles = createUseStyles({
button: {
background: "orange",
color: "white",
padding: 10
}
});
function App() {
const classes = useStyles();
return <button className={[Link]}>JSS Button</button>;
}
4. Comparison Table
Approach Scope Dynamic Styling Ease of Use Example Usage
Traditional CSS Global ❌ Easy Small apps
CSS Modules Local ❌ Moderate Medium projects
Inline Styling Local ✅ Easy Quick dynamic styles
Styled Components Local ✅ Moderate Large apps with theming
Emotion / JSS Local ✅ Moderate Scalable projects
5. Best Practices
• Use CSS Modules or CSS-in-JS for large-scale apps (to avoid conflicts).
• Keep consistent naming conventions (BEM, camelCase).
• Use theming for consistent colors, spacing, typography.
• Avoid mixing too many approaches in the same project.
• Prefer CSS-in-JS when you need dynamic styles and theming.
PROJECT: DEVELOPING A DYNAMIC USER INTERFACE FOR A WEB APPLICATION USING
REACT
1. Introduction
• Dynamic User Interfaces (UIs) update automatically based on user interactions and
data changes.
• React is widely used to build dynamic UIs because it:
o Uses a component-based architecture.
o Utilizes a virtual DOM for fast updates.
o Supports state management for interactive features.
o Enables reusability and scalability.
This project focuses on creating a dynamic React-based UI where components respond to
user input and data changes in real time.
2. Project Objectives
• Learn to build and structure a React project.
• Develop reusable UI components (e.g., buttons, forms, cards).
• Use props and state to make the UI dynamic.
• Handle user input and events (e.g., form submission, button clicks).
• Apply styling techniques for a professional look.
• Demonstrate real-time updates using React’s state management.
3. Project Setup
Step 1: Create React Project
• Use Create React App (CRA) or Vite:
npx create-react-app dynamic-ui
cd dynamic-ui
npm start
Step 2: Project Structure
dynamic-ui/
│── public/
│── src/
│ ├── components/ # Reusable UI components
│ ├── pages/ # Pages (Home, Dashboard, etc.)
│ ├── [Link] # Main component
│ ├── [Link] # Entry point
│── [Link]
4. Key Features to Implement
A) Reusable Components
• Button Component: Customizable with props (label, color, onClick).
• Card Component: Display dynamic data (e.g., user profile, product info).
• Form Component: Capture user input dynamically.
B) Handling State and Props
• Props → pass data from parent to child (read-only).
• State → manage dynamic data within a component (mutable).
Example: Counter Component
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
👉 UI updates dynamically when state changes.
C) Handling User Input and Events
Form Example:
import React, { useState } from "react";
function UserForm() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
[Link]();
alert(`Hello, ${name}!`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={(e) => setName([Link])}
/>
<button type="submit">Submit</button>
</form>
);
}
export default UserForm;
👉 Input value is controlled by React state, ensuring dynamic behavior.
D) Rendering Dynamic Data
• Use .map() to render lists dynamically.
Example: Displaying Users
const users = ["Alice", "Bob", "Charlie"];
function UserList() {
return (
<ul>
{[Link]((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
);
}
E) Styling Components
• Apply CSS Modules, Styled Components, or TailwindCSS.
• Example with inline style:
const cardStyle = { border: "1px solid #ccc", padding: "10px", borderRadius: "8px" };
function Card({ title, description }) {
return (
<div style={cardStyle}>
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
5. Example Mini Project: Dynamic Dashboard
Features:
• Navbar (navigation component).
• User List (rendered dynamically).
• Form (add new users dynamically).
• Counter Widget (shows state updates).
Flow:
1. User enters a name in form.
2. On submit, name is added to the user list dynamically.
3. UI updates without page reload.
6. Best Practices
• Break UI into small reusable components.
• Use state lifting if multiple components share data.
• Use prop-types or TypeScript for type safety.
• Keep UI consistent with component libraries (Material-UI, Ant Design).
• Optimize performance with [Link] and shouldComponentUpdate (class
components).
7. Summary
• A dynamic UI in React responds to state changes and user input in real time.
• Key techniques:
o Components (reusable, modular UI).
o Props & State (data flow and reactivity).
o Event Handling (user interaction).
o Styling Approaches (CSS, CSS Modules, CSS-in-JS).
• This project demonstrates how React’s component-based approach simplifies
building interactive, scalable, and reusable UIs.