Lms Project
Lms Project
Introduction to React
❓ What is React?
Answer:
🔧 Rich Ecosystem – Includes libraries like Redux, React Router, React Query, etc.
Feature Description
JSX JavaScript + XML syntax extension used to write HTML in JS
Components Encapsulated building blocks of UI
Virtual DOM Improves performance by diffing and updating the real DOM
Unidirectional Data Flow Predictable state management
Hooks Allows using state and other features in functional components
Declarative UI Describe what the UI should look like at any point in time
✅ 2. Environment Setup
❓ How do you install Node.js and npm for React development?
Answer:
To build React applications, you need to have Node.js and npm (Node Package
Manager) installed on your system because:
Tools like Create React App (CRA) use Node.js for building and running the dev
server.
🔧 Steps to Install:
Visit: https://nodejs.org
Verify installation:
bash
Copy
Edit
node -v
npm -v
Example output:
node -v → v20.11.0
npm -v → 10.2.3
❓ How to create a new React project using Create React App (CRA)?
Answer:
📦 Step-by-step:
bash
bash
my-app/
├── node_modules/
├── public/
│ └── index.html
├── src/
│ ├── App.js
│ ├── App.css
│ ├── index.js
│ └── ...
├── .gitignore
├── package.json
├── README.md
└── ...
❓ What is the difference between npm install, npm start, and npm run build?
Command Purpose
npm install Installs all dependencies listed in package.json
npm start Starts the development server (localhost:3000)
npm run build Compiles the app into production-ready files (build/ folder)
JSX stands for JavaScript XML. It is a syntax extension for JavaScript used in
React to describe how the UI should look. It allows you to write HTML-like code
inside JavaScript, which makes the code more readable and declarative.
Behind the scenes, JSX is transpiled by Babel into plain JavaScript using
React.createElement() calls.
jsx
js
❗ Example:
jsx
<div>
<h1>Hello</h1>
<p>Welcome to React!</p>
</div>
❓ What are the rules/syntax of JSX?
Answer:
✅ Only One Root Element: JSX expressions must have a single parent element.
jsx
return (
<div>
<h1>Hi</h1>
<p>Welcome</p>
</div>
);
✅ Use className instead of class:
jsx
<div className="container">Hello</div>
✅ Self-closing Tags:
jsx
jsx
<p>Hello {name}</p>
✅ JSX Must Be Wrapped in () if Multiline:
jsx
return (
<div>
<h1>Heading</h1>
</div>
);
Yes! You can embed any JavaScript expression inside JSX using {}:
jsx
return (
<p>{name} is {age} years old</p>
);
✔ Valid expressions inside {}: variables, ternary operators, function calls, etc.
❌ Not allowed: if, for, while (use outside JSX or as expressions).
🧠 Improved Readability: Looks like HTML and is intuitive for frontend developers.
🔒 Safe: JSX prevents injection attacks because it escapes values before rendering.
✅ 4. Components in React
❓ What are Components in React?
Answer:
In React, components are the building blocks of the UI. Each component is a
JavaScript function or class that returns JSX. They help you split the UI into
independent, reusable pieces.
Functional Components
jsx
A functional component is a JavaScript function that returns JSX. It's the most
common way to define components in modern React, especially with the introduction
of Hooks.
jsx
Copy
Edit
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
✅ Advantages:
A class component uses ES6 class syntax. It has access to lifecycle methods like
componentDidMount, shouldComponentUpdate, etc.
jsx
props stands for properties. Props are used to pass data from a parent component to
a child component.
jsx
function Greet(props) {
return <h1>Hi, {props.name}</h1>;
}
Read-only
🔧 Usage:
jsx
function Greet(props) {
return <h1>Hello, {props.name}</h1>;
}
Greet.propTypes = {
name: PropTypes.string.isRequired,
};
✅ Benefits:
defaultProps allows you to set a default value for props in case none are provided.
jsx
Copy
Edit
Greet.defaultProps = {
name: 'Guest',
};
✔ If you render <Greet />, it will show "Hello, Guest".
When the state changes, React re-renders the component to reflect the new data on
the UI.
jsx
function Counter() {
const [count, setCount] = useState(0); // count is state
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
jsx
jsx
Lifting state up means moving state to a common parent component so that multiple
child components can share and synchronize data.
🧩 Scenario:
Two child components need access to the same piece of state → move the state to
their nearest common ancestor.
✅ Example:
jsx
function Parent() {
const [data, setData] = useState("Hello");
return (
<>
<Child1 data={data} />
<Child2 updateData={setData} />
</>
);
}
✔ This allows centralized control of state and better data flow.
✅ Summary Table
Topic Summary
State Internal data to control component
useState Hook to use state in functional components
Props vs State Props → external, State → internal
Lifting State Up Move state to a parent to share it across components
The lifecycle of a React component refers to the sequence of methods that are
invoked during the lifespan of a component — from its creation, updating, and
finally unmounting.
It mainly applies to Class Components, though similar logic can be replicated using
Hooks in Functional Components.
✅ Example:
jsx
componentDidMount() {
console.log("Component mounted!");
}
render() {
return <h1>Hello, {this.state.name}</h1>;
}
}
🔷 2. Updating Phase Methods
Lifecycle Method Purpose
static getDerivedStateFromProps() Sync state with new props
shouldComponentUpdate() Decide whether to re-render
render() Re-renders JSX
getSnapshotBeforeUpdate() Capture DOM info before update
componentDidUpdate() Executes after the update is done
✅ Example (componentDidUpdate):
jsx
componentDidUpdate(prevProps, prevState) {
if (this.state.count !== prevState.count) {
console.log("Count has changed");
}
}
🔷 3. Unmounting Phase Method
Lifecycle Method Purpose
componentWillUnmount() Cleanup before component is removed
✅ Used for:
Clearing intervals
jsx
Copy
Edit
componentWillUnmount() {
clearInterval(this.timer);
}
🔷 Summary of Lifecycle Methods (Class)
Phase Method Name(s)
Mounting constructor, render, componentDidMount
Updating shouldComponentUpdate, componentDidUpdate
Unmounting componentWillUnmount
✅ 7. Hooks in React
❓ What are Hooks in React?
Answer:
Hooks are special functions in React that let you use state and other React
features (like lifecycle methods) in functional components — which was not possible
before React 16.8.
With hooks, you can avoid writing class components and still use powerful features
like:
Context (useContext)
References (useRef)
Hook Description
useState Add state to functional components
useEffect Handle side effects like API calls, DOM updates
useContext Use context (global state/data)
useRef Create references to DOM or persist values
useMemo Memoize expensive calculations
useCallback Memoize functions
useReducer Manage complex state logic (like Redux)
🔷 1. useState Hook
jsx
🔷 2. useEffect Hook
useEffect handles side effects such as:
Fetching data
Event listeners
DOM manipulation
Timers
jsx
useEffect(() => {
console.log("Component mounted");
return () => {
console.log("Component will unmount");
};
}, []);
Dependency Array Behavior
[] Runs once after mount (like componentDidMount)
[var] Runs when var changes (like componentDidUpdate)
Omitted Runs after every render
🔷 3. Rules of Hooks
Hooks must follow specific rules:
✅ Summary Table
Hook Description
useState Manage state
useEffect Manage side effects
useContext Access context
useRef Store mutable values without re-render
useMemo Cache expensive calculations
useCallback Cache functions
useReducer Like Redux for local state
✅ Example:
jsx
function ClickMe() {
const handleClick = () => {
alert("Button clicked!");
};
function InputBox() {
const [name, setName] = useState("");
return (
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
✅ e.target.value gets the updated value of the input field.
function FormExample() {
const handleSubmit = (e) => {
e.preventDefault(); // prevent page reload
console.log("Form submitted");
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
🔷 4. Handling Events in Class Components (with this Binding)
jsx
handleClick() {
this.setState({ clicked: true });
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
✅ In class components, you must bind this in the constructor or use arrow
functions.
User input
State or props
jsx
function Greet({ isLoggedIn }) {
return (
<h1>
{isLoggedIn ? "Welcome back, Rushikesh!" : "Please log in"}
</h1>
);
}
✅ Best for simple if/else in JSX.
jsx
jsx
🔚 Summary
Technique When to Use
if/else Outside JSX, multiple conditions
? : (ternary) Inline in JSX, simple condition
&& Only render when true
switch Multiple exact condition cases
Would you like to continue with:
In React, lists are rendered using the JavaScript .map() method to iterate over
arrays and return JSX elements. It helps display dynamic data like tasks, products,
users, etc.
function FruitList() {
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
map() loops through fruits
function UserList() {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
✅ Always use unique key (like id) to improve performance and prevent rendering
bugs.
🔺 Don't use index as key unless the list is static or won’t change.
function ProductList() {
return (
<div>
{products.length === 0 ? (
<p>No products available</p>
) : (
<ul>
{products.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
)}
</div>
);
}
🔷 5. Nesting .map() with Components
jsx
Copy
Edit
function User({ name }) {
return <li>{name}</li>;
}
function UserList() {
const users = ["Rushikesh", "Priya", "Ravi"];
return (
<ul>
{users.map((name, i) => (
<User key={i} name={name} />
))}
</ul>
);
}
Forms in React are used to collect user input. React uses controlled components,
where form elements like <input> and <textarea> are bound to component state using
the useState hook. React handles the form data instead of the DOM.
🔷 1. Controlled Components
In controlled components, form data is handled by React state.
jsx
Copy
Edit
import { useState } from "react";
function ControlledForm() {
const [name, setName] = useState("");
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
value binds input to state
🔷 2. Uncontrolled Components
In uncontrolled components, React does not control the input value. We use useRef
to access the DOM directly.
jsx
Copy
Edit
import { useRef } from "react";
function UncontrolledForm() {
const inputRef = useRef();
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
Direct DOM manipulation using ref
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
</form>
);
}
🔷 4. Form Validation Example
jsx
Copy
Edit
function ValidatedForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{error && <p style={{ color: "red" }}>{error}</p>}
<button>Submit</button>
</form>
);
}
Q1: What are forms in React and why are they important?
Answer:
Forms in React are used to capture user input — such as login information,
registration data, search queries, or feedback — and process or store this
information.
React allows full control over form input values via state.
You can perform dynamic actions (e.g., disabling the submit button until the form
is valid).
Any changes to the form input are handled via onChange, which updates the state.
Example:
jsx
function ControlledForm() {
const [name, setName] = useState("");
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
In this example:
Q3: How does onChange and value binding work in controlled components?
Answer:
onChange event handler: Updates that state whenever the user types or selects
something.
This ensures that the form field is always in sync with the component’s internal
state. This is useful for:
Real-time validation.
Disabling/enabling buttons.
Use the state values to perform operations (e.g., display or send to server).
Example:
jsx
Validate data.
Use a single state object and update fields dynamically using the name attribute.
Example:
jsx
jsx
Q6: What is the difference between controlled and uncontrolled components in React?
Feature Controlled Component Uncontrolled Component
State management React state via useState or props DOM handles its own state
value binding Yes No
onChange handler Required Optional
Example usage Forms with validation and logic Quick input without need to
track
Ref usage Not required Uses useRef to get value
Q7: What are best practices while working with forms in React?
Use controlled components for better control and validation.
Use form libraries like Formik or React Hook Form for complex form logic.
React’s Declarative UI
✅ Q1. What is Data Binding in React? Explain One-way Data Binding with example.
Answer:
Data binding in React refers to the connection between the component's state (data)
and the UI (view). React follows one-way data binding, meaning the data flows from
the component (state/props) to the UI only.
This makes the UI predictable, easier to debug, and maintainable because the state
is the single source of truth.
➡️
Flow: Component (State/Props) UI (DOM)
🔸 Example:
jsx
function NameDisplay() {
const [name, setName] = useState("Rushikesh");
return (
<div>
<h1>Hello, {name}</h1>
<button onClick={() => setName("Pawar")}>Change Name</button>
</div>
);
}
➡️ In this example, clicking the button updates the state name, which automatically
updates the UI.
React is declarative, meaning we describe what the UI should look like for a given
state, and React takes care of updating the DOM to match that state.
We don’t manually update the DOM like in jQuery; instead, we define the UI output
based on state/props.
🟢 Example:
jsx
✅ Q3. What is the difference between One-Way and Two-Way Data Binding? (React vs
Angular)
Feature React (One-Way) Angular (Two-Way)
Data Flow Direction One-Way (Component ➝ UI) Two-Way (Component ⬌ UI)
DOM Update Control Manual via setState or useState Automatic using
[(ngModel)]
Predictability More predictable and easier to debug Less predictable due to
automatic updates
Flexibility & Debugging Easier to track changes Harder to trace which side changed
the data
Syntax Example value={inputValue} + onChange [(ngModel)]="inputValue"
jsx
Copy
Edit
function TwoWayBinding() {
const [text, setText] = useState("");
return (
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
);
}
Here, the value reflects the state, and onChange updates the state → simulating
two-way data sync.
✅ Summary:
React uses one-way binding, improving predictability and debugging.
Would you like to continue to the next topic — 13. React Router?
📘 Subtopics Covered:
Link vs a
Nested Routing
React Router is a standard routing library for React that enables navigation among
views of various components in a React application.
React is a Single Page Application (SPA), which means it doesn’t reload the entire
page when navigating between different views. React Router helps us manage these
views without full page reloads.
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
jsx
// App.js
import React from "react";
import { Routes, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
return (
<div>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
}
function Login() {
const navigate = useNavigate();
jsx
Copy
Edit
<Route path="/user/:id" element={<User />} />
function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
jsx
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
jsx
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet /> {/* Nested routes appear here */}
</div>
);
}
✅ Summary:
Use React Router for SPA navigation
React Router is a standard routing library for React applications that enables
navigation among different components without reloading the entire page. It helps
build Single Page Applications (SPAs) by allowing the user to switch between views
while maintaining the app's state.
React Router uses components like <BrowserRouter>, <Routes>, <Route>, <Link>, and
<Navigate> to manage navigation and URL mapping.
Key benefits:
A Single Page Application (SPA) is a web app that loads a single HTML page and
dynamically updates content without refreshing the entire page. SPAs use JavaScript
to control routing and rendering on the client side.
In React, SPAs use React Router to manage navigation between views without
contacting the server for each route. This improves speed and user experience.
Example:
Visiting /home and then /about doesn’t reload the entire page.
bash
<BrowserRouter> is a component that uses the HTML5 History API to keep the UI in
sync with the URL. It is the root container that wraps the whole routing structure.
Example:
jsx
<BrowserRouter>
{/* All Routes go here */}
</BrowserRouter>
Q5: What is the use of <Routes> and <Route>?
Answer:
Example:
jsx
Copy
Edit
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
Here:
Instead of using <a> tags, use the <Link> component to navigate between pages in
React without reloading the page.
Example:
jsx
<Link to="/">Home</Link>
<Link to="/about">About</Link>
This updates the URL and renders the component associated with that route.
jsx
React Router provides the useNavigate() hook for navigation within functions:
jsx
function MyComponent() {
const navigate = useNavigate();
Nested Routing allows routes to be defined inside other routes, enabling layouts or
child pages.
Example:
jsx
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
Visiting /dashboard/profile renders Profile inside the Dashboard.
jsx
<Outlet />
This placeholder renders child components.
jsx
jsx
import './App.css';
CSS Modules – Locally scoped styles.
jsx
jsx
jsx
Example:
jsx
// App.module.css
.title {
color: red;
}
// App.js
import styles from './App.module.css';
<h1 className={styles.title}>Hello</h1>
❓ Q3: Which styling method is best in React?
✅ Answer:
It depends on your project:
Use Inline Styles for dynamic styles.
Use Styled-Components or Tailwind CSS for modern, scalable styling with reusable
components or utility classes.
Key principles:
State is Read-Only
Component Description
Store Holds the state of the app
Actions Objects that describe events
Reducers Functions that update the state
Dispatch Sends actions to reducers
Selectors Read data from the store
UI triggers an action →
Action is dispatched →
You need a global state (like user login, dark mode, cart).
The app has predictable flows that benefit from strict control.
❓ Q1: What are Bundlers in React, and why are they important?
🟢 Answer:
Bundlers are tools that package all JavaScript, CSS, and other files into a single
or smaller number of optimized files to be served to the browser. In React, tools
like Webpack, Vite, or Parcel act as bundlers. They allow developers to write
modular code across multiple files but deliver a fast, compact version to users.
✅ Benefits of bundlers:
❓ Q2: What is the folder and file structure in a React project created with Create
React App?
🟢 Answer:
A standard CRA (Create React App) folder structure looks like this:
pgsql
Copy
Edit
my-app/
├── node_modules/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── App.js
│ ├── App.css
│ ├── index.js
│ └── components/
│ └── MyComponent.js
├── package.json
├── .gitignore
└── README.md
Key folders:
components/
pages/
hooks/
context/
utils/
Example:
jsx
Copy
Edit
function Button({ text, onClick }) {
return <button onClick={onClick}>{text}</button>;
}
You can now use <Button text="Submit" /> and <Button text="Cancel" /> anywhere in
your app with different props.
🔁 Advantages:
Faster development.
🧠 Techniques:
Code-splitting with React.lazy and Suspense to load components only when needed.
Use pagination or virtualization for large lists (e.g., with react-window or react-
virtualized).
❓ Q5: What are React Developer Tools and how are they used for debugging?
🟢 Answer:
React Developer Tools is a browser extension (available for Chrome & Firefox) that
helps inspect React component trees, props, and state.
📦 Installation:
You can install from the browser extension store by searching "React Developer
Tools".
✅ Summary:
Concept Key Points
Bundlers Combine and optimize JS/CSS for the browser
Folder Structure Organize code with src/, components/, etc.
Reusability Write once, use anywhere
Performance Optimize renders with memo, lazy loading
DevTools Inspect components, props, state, and performance
Recommended structure:
graphql
Copy
Edit
src/
│
├── assets/ # Images, fonts, icons, etc.
├── components/ # Reusable UI components
│ └── Button/
│ ├── Button.jsx
│ └── Button.css
│
├── pages/ # Page-level components
│ └── Home.jsx
│ └── About.jsx
│
├── layout/ # Common layouts like Navbar, Footer
├── hooks/ # Custom React hooks
├── context/ # React Context providers
├── services/ # API calls and logic
├── utils/ # Utility/helper functions
├── App.jsx
├── index.js
Benefits:
✅ Q2: What are some best practices for component reusability in React?
Answer:
Component reusability makes the code DRY (Don't Repeat Yourself) and easier to
maintain.
Best Practices:
Example:
jsx
Copy
Edit
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
Now this Button can be reused across your app with different label and onClick
handlers.
React apps may face performance issues as they grow. These practices help in
optimizing them:
React.memo()
useMemo()
useCallback()
✅ Q4: What are React Developer Tools and how do they help in debugging?
Answer:
Key Features:
Why useful?
✅ Q5: What are some general coding best practices in React development?
Answer:
Write unit and integration tests using Jest & React Testing Library.