Unit-3
Unit-3
Key Features:
Verify Installation:
Conditional Rendering:
JSX supports conditional rendering using JavaScript constructs like if statements,
ternary operators, or logical operators.
Attributes in JSX:
Attributes in JSX are written similarly to HTML, but with camelCase for property
names (e.g., className instead of class, onClick instead of onclick).
function getGreeting(user) {
if (user) {
return <h1>Hello, {user}!</h1>;
}
return <h1>Hello, stranger.</h1>;
}
Fragments:
In JSX, we can use fragments (<>...</>) to group elements without adding extra
nodes to the DOM.
return (
<>
<h1>Heading</h1>
<p>This is a paragraph.</p>
</>
);
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
1. Functional Components:
These are JavaScript functions that accept props (input data) and return
React elements to describe what should appear on the screen.
Functional components are simpler and preferred in modern React
development.
They can use React Hooks (like useState, useEffect, etc.) to handle state and
lifecycle methods.
Example of a functional component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
2. Class Components:
These are ES6 classes that extend from React.Component. They have a
render() method that returns React elements.
Class components also handle state and lifecycle methods directly inside the
class.
Class components were more commonly used in older versions of React, but
are less favored now due to the introduction of hooks in functional
components.
Example of a class component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Key Features of React Components:
❖ Reusable: Components can be reused in different parts of the app.
❖ Isolated: Each component manages its own state and logic, making them
self-contained.
❖ Composable: Components can be composed together, meaning you can
nest components inside other components to build complex UIs.
❖ Stateful vs Stateless: Functional components are considered stateless
unless they use hooks to manage local state. Class components manage
state directly through this.state.
❖ Props: Components receive input in the form of props (properties), which
are read-only. These are used to pass data from parent to child
components.
Rendering in React refers to the process of displaying components and their content
to the user interface (UI). React uses a virtual DOM to efficiently manage updates to
the UI, ensuring high performance and reactivity. Here’s an overview of how
rendering works in React:
Types of Rendering
• Initial Rendering:
o Happens when the application or a component is first loaded.
o React builds the virtual DOM and calculates the changes needed to
render the real DOM.
• Re-Rendering:
o Occurs when the component’s state or props change.
o React compares the current and previous virtual DOM using a
process called reconciliation and updates only the parts of the DOM
that changed.
Rendering Lifecycle
• Functional Components:
o Rendering is tied to the function call of the component.
o Any update to state or props triggers the component to re-render.
• Class Components:
o Controlled by the render() method.
o The render() method is called every time setState() is used or props are
updated.
Virtual DOM
• React maintains a lightweight copy of the real DOM, called the virtual DOM.
• When state or props change:
1. React computes the updated virtual DOM.
2. It uses diffing to identify changes between the previous and current
virtual DOM.
3. Only the necessary updates are applied to the real DOM.
This approach minimizes expensive DOM manipulation operations, enhancing
performance.
Key Concepts in Rendering
• Props:
o Data passed from parent to child components.
o Changes in props trigger the child component to re-render.
• State:
o Internal data managed within a component.
o Changes to state trigger the component to re-render.
• Keys:
o Used in lists to help React identify which items have changed, are
added, or removed.
o Improves rendering performance for lists.
• Pure Components and Memoization:
o React.PureComponent or React.memo() can be used to prevent
unnecessary re-renders by doing a shallow comparison of props and
state.
Optimizing Rendering
• Avoid unnecessary renders by:
o Using React.memo() for functional components.
o Using shouldComponentUpdate() for class components.
o Keeping state localized to minimize prop drilling.
• Use code-splitting and lazy loading for better performance.
• Avoid inline functions or objects in props to prevent new references during
every render.
State
State is an object that represents the dynamic parts of a component. It determines
how a component behaves and what it renders. It is mutable and is managed within
the component.
Key Features
Local to the Component: State is owned and managed by the component itself.
Dynamic: Changes to state trigger a re-render of the component.
Initialized within the Component: State is typically initialized when the component
is created.
increment = () => {
this.setState({ count: this.state.count + 1 }); // Update state
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Declare state
Updating State
In functional components:
setCount((prevCount) => prevCount + 1);
Props
Props (short for properties) are used to pass data from a parent component to a child
component. They are read-only and cannot be modified by the child component.
Key Features
Immutable: Props are immutable, meaning they cannot be changed by the receiving
component.
Parent to Child Communication: Props are used to send data or functions to child
components.
Stateless: Props do not maintain their own state.
Using Props
Props are passed to a child component as attributes of the component tag.
Example:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return <Greeting name="John" />;
}
Default Props
we can define default props for a component.
Example:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
Greeting.defaultProps = {
name: 'Guest', // Default value for 'name'
};
function App() {
return <Greeting />;
}
State vs. Props
Parent Component:
function App() {
return <Profile name="John Doe" age={30} />;
}
return (
<div>
<h1>Name: {name}</h1>
<h2>Age: {age}</h2>
<p>Likes: {likes}</p>
<button onClick={incrementLikes}>Like</button>
</div>
);
}
Note
❖ Use state for data that changes during the component's lifecycle.
❖ Use props for data or callbacks that need to be shared between components.
❖ Keep components as pure as possible: Minimize state in components and use
props for configuration.
❖ Avoid directly modifying state; always use setState or useState.
In React, lifecycle methods allow developers to hook into specific points of a
component's lifecycle. The lifecycle of a React component can be divided into three
phases:
constructor(props):
Called when the component is first created. Often used to initialize state or bind
event handlers.
static getDerivedStateFromProps(props, state):
Rarely used, but allows the state to be updated based on changes to props. It’s
invoked before rendering and also when props change during updates.
render():
Required method in class components. It reads props and state and returns the JSX
(UI) that gets rendered to the DOM.
componentDidMount():
Called once the component has been rendered and inserted into the DOM. Commonly
used for side effects like data fetching or subscriptions.
2. Updating Phase
These methods are called when the component is being re-rendered as a result of
changes to its props or state.
This method is also called during the updating phase, just before rendering.
shouldComponentUpdate(nextProps, nextState):
Used to optimize re-rendering. It lets you compare the current props and state with
the next ones and return true or false to control whether the component should
update.
render():
getSnapshotBeforeUpdate(prevProps, prevState):
Called right before the DOM is updated. It can capture information (like scroll
position) before the DOM is actually changed.
componentDidUpdate(prevProps, prevState, snapshot):
Called after the component's updates are flushed to the DOM. It’s often used for DOM
updates or further side effects after changes.
3. Unmounting Phase
These methods are called when the component is being removed from the DOM.
componentWillUnmount():
Called just before the component is removed from the DOM. It’s commonly used for
cleanup, such as removing event listeners or cancelling network requests.
static getDerivedStateFromError(error):
componentDidCatch(error, info):
Called after an error is thrown, allowing you to log error information or display
fallback UI.
Forms and User Input
Forms in React are used to collect user input. React uses a declarative approach
where form elements are controlled or uncontrolled.
Controlled Components
▪ In a controlled component, React state is the "single source of truth."
▪ An input form element’s value is controlled by React via state.
Example:
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
Uncontrolled Components
▪ Uncontrolled components store their values in the DOM instead of state.
▪ React’s ref is used to access the value.
Example:
import React, { useRef } from 'react';
function UncontrolledForm() {
const nameInput = useRef();
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={nameInput} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
function MultiInputForm() {
const [formData, setFormData] = useState({ firstName: '', lastName: '' });
return (
<form>
<input name="firstName" value={formData.firstName} onChange={handleChange} />
<input name="lastName" value={formData.lastName} onChange={handleChange} />
</form>
);
}
Event Handling
React has a unified system for handling events, where event names are written in
camelCase (e.g., onClick).
Key Features
❖ React uses Synthetic Events (a wrapper around native browser events) for
consistency across browsers.
❖ Event handlers in React are passed as functions, not strings.
Common Events
Example: Handling Clicks
function ButtonClick() {
const handleClick = () => {
alert('Button clicked!');
};
Passing Arguments
To pass arguments to an event handler, use an inline function.
function PreventDefaultForm() {
const handleSubmit = (event) => {
event.preventDefault(); // Stops default behavior
alert('Form submission prevented.');
};
function MouseTracker() {
const handleMouseMove = (event) => {
console.log(`Mouse at: (${event.clientX}, ${event.clientY})`);
};
Integration Example
A form with controlled components and event handling:
function FullForm() {
const [formData, setFormData] = useState({ username: '', password: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input name="username" value={formData.username}
onChange={handleChange} />
</label>
<label>
Password:
<input name="password" type="password" value={formData.password}
onChange={handleChange} />
</label>
<button type="submit">Login</button>
</form>
);
}
Note:
❖ Use controlled components for better state management.
❖ Use ref for accessing DOM nodes in uncontrolled components.
❖ Use preventDefault() for overriding default behaviors (like form submissions).
❖ Organize event handlers outside the JSX for readability and reusability.