Department Of Computer Applications,
National Institute of Technology, Kurukshetra
Haryana, India
Interoperable Web Technologies
Assignment
Submitted by:- Submitted to:
Name: Manpreet Singh Chandi Dr. Munish Bhatia
Roll No: 52212107
Group: G3
1
Conditional Rendering in React
Conditional rendering in React refers to the practice of rendering different UI
elements or components based on certain conditions. This allows developers
to dynamically display content or components in response to changes in
application state, user interactions, or other factors.
In other words, conditional rendering means showing different parts of the UI
based on specific conditions being met or not. It's a fundamental concept that
enables you to build dynamic and interactive user interfaces. For example, we
might want to display a "Login" button if the user is not logged in, and a
"Logout" button if they are logged in.
There are various methods by which we can achieve conditional rendering,
some are given below:
1. Using if statements: We can use regular JavaScript `if` statements
inside your components to conditionally render different elements or
components.
Example:
function NewComponent({ isLoggedIn }) {
if (isLoggedIn) {
return <LogInComponent />;
} else {
return <LogOutComponent />;
}
}
2
2. Using ternary operator: This is a concise way to write conditional
rendering in React, using the `?` and `:` operators to create a
conditional expression.
Example:
function NewComponent({ isLoggedIn }) {
return isLoggedIn ? <LogInComponent /> :
<LogOutComponent />;
}
3. Using logical && operator: The logical `&&` operator can be used to
conditionally render a component based on a boolean expression.
Example:
function NewComponent({ isLogIn }) {
return isLogIn && <LogInComponent />;
}
4. Using conditional rendering with logical OR: You can use logical
OR (`||`) to provide a default value if a certain condition is not met.
Example:
function NewComponent({ user }) {
const username = user.username || 'Guest User';
return <p>Welcome, {username}!</p>;
}
5. Using switch statements: In more complex scenarios, you might want
to use switch statements for conditional rendering, especially when
there are multiple possible conditions.
3
Example:
function NewComponent({ status }) {
switch (status) {
case 'loading':
return <LoadingComponent />;
case 'success':
return <SuccessComponent />;
case 'error':
return <ErrorComponent />;
default:
return null;
}
}
Conditional rendering in React is managed by evaluating the conditions inside
the component's render function. React uses a virtual DOM to efficiently
update the actual DOM, and it re-renders components whenever their state or
props change.
Here's how conditional rendering is managed in React:
1. Evaluation of Conditions: Inside the component's render function,
conditions are evaluated using JavaScript expressions. These conditions can be
based on the component's state, props, or any other variables.
2. Reconciliation: When the conditions change (for example, due to state
updates or new props being passed), React compares the new virtual DOM
representation with the previous one in a process called reconciliation.
4
3. Update of Virtual DOM: React updates the virtual DOM to reflect the
changes in state or props. It identifies which parts of the virtual DOM need to
be updated based on the changes in the component's state or props.
4. Efficient DOM Updates: React then updates the actual DOM only for the
parts of the virtual DOM that have changed. This makes the rendering process
efficient, as it avoids unnecessary updates to the DOM.
5. Component Lifecycle Methods: During the rendering process, React also
invokes certain lifecycle methods of the component, such as
`componentDidUpdate`, which allows us to perform additional logic after the
component has been re-rendered.
6. Performance Optimization: React's reconciliation algorithm optimizes the
rendering process by minimizing DOM updates and ensuring that only the
necessary changes are applied. This helps in maintaining good performance,
even for complex UIs with frequent updates.
Events in React
An event is an action that could be triggered as a result of the user action or
system generated event. For example, a mouse click, loading of a web page,
pressing a key, window resizing, and other interactions are called events.
React has its own event handling system which is very similar to handling
events on DOM elements. The react event handling system is known as
Synthetic Events. The synthetic event is a cross-browser wrapper of the
browser's native event.
5
Handling events with react has some syntactic differences from handling
events on DOM. These are:
1. React events are named as camelCase instead of lowercase.
2. With JSX, a function is passed as the event handler instead of a string.
For example:
Event declaration in plain HTML:
<button onclick="showMessage()">
Hello JavaTpoint
</button>
Event declaration in React:
<button onClick={showMessage}>
Hello JavaTpoint
</button>
React events can include user actions like clicking a button, typing in an input
field, hovering over an element, or system events like component lifecycle
events. These events are attached to specific elements in the DOM and are
handled using event handlers, which are functions that execute in response to
the event being triggered.
Here are some key points about React events:
1. Synthetic Events: React uses its own synthetic event system instead of
native browser events.
2. Event Handlers: Event handlers are functions that are called when a
specific event occurs. In React, event handlers are typically defined as props
on JSX elements and are written using camelCase naming convention, similar
to HTML event attributes.
6
3. Event Propagation: React follows the same event propagation model as
the native browser events, including the capturing and bubbling phases. We
can use event methods like `stopPropagation()` and `preventDefault()` to
control event propagation and behavior.
4. Handling Events: React components can handle events by defining event
handler functions and attaching them to specific elements using JSX syntax.
Event handlers can be defined inline, as class methods, or as arrow functions
depending on the use case and coding style.
5. Supported Events: React supports a wide range of events, including mouse
events (`onClick`, `onMouseMove`, `onMouseOver`, etc.), keyboard events
(`onKeyDown`, `onKeyPress`, `onKeyUp`), form events (`onChange`,
`onSubmit`, `onFocus`, `onBlur`).
Event handling in React is managed through a combination of React's
synthetic event system and the component lifecycle. Here's how it's managed:
1. Event Registration: When you define an event handler in a React
component, such as `onClick`, React attaches an event listener to the
corresponding DOM element.
2. Event Propagation: When an event is triggered, React's synthetic event
system intercepts it and wraps it in a synthetic event object. This object
contains information about the event, such as the type, target element, and any
additional data related to the event.
3. Event Handling: React calls the event handler function that we've
provided, passing the synthetic event object as an argument. We can then
access properties of the synthetic event object to handle the event, such as
`event.target.value` for form input elements.
4. Component Re-rendering: If the event handler modifies the component's
state or props, React will re-render the component to reflect the changes. This
includes any updates to the UI that are triggered by the event handler.
7
5. Event Pooling: React optimizes event handling by pooling and reusing
synthetic event objects. This helps to reduce memory usage and improve
performance, especially in scenarios where events are triggered frequently.
6. Event Delegation: React leverages event delegation to efficiently handle
events on large numbers of DOM elements. Instead of attaching event listeners
to each individual element, React attaches a single event listener to a parent
element and uses event bubbling to determine which child element triggered
the event.