REACT JS Mid-1 AssignmentQuestion&Answers-CSD
REACT JS Mid-1 AssignmentQuestion&Answers-CSD
Unit-I
React is a powerful JavaScript library for building fast, scalable front-end applications. Created
by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual
DOM,enabling efficient UI updates and a seamless user experience.
Applications:
Facebook, popular social media application − React was originally developed at Facebook (or
Meta), so its only natural that they use it to run their application. As for their mobile application, it
uses React Native to display Android and iOS components, instead of DOM. Facebook's codebase
now includes over 20,000 components and uses the React version that is public.
Instagram, popular photo sharing application − Instagram is also completely based on React, as
it is powered by Meta as well. The main features to show its usage include Geo-locations,
Hashtags, Google Maps APIs etc.
Netflix, popular media streaming application − Netflix switched to React in 2015. The factors
that mainly influenced this decision are the 1) startup speed to reduce the processing time to render
the homepage and enabling dynamic elements in the UI, 2) modularity to allow various features
that must coexist with the control experience and 3) runtime performance for efficient UI
rendering.
Code Academy, popular online training application − Code Academy uses React as the "script
is battle-tested, easy to think about, makes SEO easy and is compatible with legacy code and
flexible enough for the future".
Reddit, popular content sharing application − Reddit is also developed using React from the
scratch.
General-purpose scripting for web development Specialized for building user interfaces (UIs) in
web apps
Broad ecosystem of libraries and frameworks Rich ecosystem with React-specific tools and
libraries
Widely used across web and server environments Specifically for front-end UI development
1. Component-Based Architecture
React follows a component-based architecture, where the UI is broken
down into smaller, reusable components. Each component is a self-
contained unit that can have its own state and logic. This modular
approach leads to cleaner, more maintainable code and makes it easier to
build large-scale applications. Components can be reused across different
parts of the application or even in different projects.
One of the key innovations that set React apart is its use of the Virtual DOM. Instead of directly
updating the browser’s DOM, React first makes changes in a lightweight virtual representation of
the DOM. It then compares this new virtual DOM with the previous version (a process called
"reconciliation") and only updates the parts of the actual DOM that have changed. This improves
the performance of the application, as it minimizes the number of updates to the browser's DOM.
3.Unidirectional Data Flow
React enforces a one-way data flow. The data in a React application flows from parent components to
child components through "props." This helps to manage the state more effectively, leading to better
control over the application’s behavior. Developers can track the flow of data and make applications
more predictable.
4.JSX Syntax
React uses JSX (JavaScript XML), which allows developers to write HTML-like code directly within
JavaScript. JSX combines the flexibility of JavaScript with the ease of writing HTML, making it easier
for developers to define components and render them. JSX enhances the readability and
maintainability of code while offering the full power of JavaScript.
5.React Hooks
React Hooks, introduced in React 16.8, allow developers to use state and other React features without
writing class components. Hooks like useState, useEffect, and useContext enable functional
components to handle state management and side effects. This reduces boilerplate code and simplifies
the logic of components.
6.Rich Ecosystem and Community
React has a large, active community of developers and contributors. The ecosystem is filled with
libraries and tools that complement React, such as React Router for routing, Redux for state
management, and React Query for data fetching. The vast number of resources, tutorials, and third-
party libraries make it easier for developers to get started and solve problems quickly.
React elements
React elements are the smallest building blocks of React applications.
They are plain JavaScript objects that describe what you want to see on the screen.
Unlike browser DOM elements, React elements are immutable and efficient to create
To render this element into the DOM, you need a root DOM node, typically a <div> with an id of
"root".
You can then use ReactDOM.createRoot() and root.render() to display the element:
const root=ReactDOM.createRoot(document.getElementById('root'));
root.render(element);
This will display "Hello, world!" on the page
JSX
JSX, short for JavaScript XML, is a syntax extension for JavaScript that allows developers to write
HTML-like code directly within JavaScript.It is primarily used in React to define the structure of user
interfaces.While JSX resembles HTML, it is not HTML but a syntax that React transforms into JavaScript
objects.
HTML-like Syntax in JavaScript: JSX enables embedding HTML-like tags directly in JavaScript
code.
For example:
const element = <h1>Hello, World!</h1>;
Embedding JavaScript Expressions: JavaScript expressions can be embedded within JSX using curly
braces {}.
For example:
const name = "React";
const element = <h1>Welcome to {name}!</h1>;
Attributes in JSX: Attributes in JSX are similar to HTML but follow JavaScript conventions.
For instance:
Use className instead of class (since class is a reserved keyword in JavaScript). Use camelCase for
attributes like htmlFor instead of for.
One Parent Element: JSX requires all elements to be wrapped in a single parent element. You can use
a <div> or a React fragment (<>...</>) to achieve this:
const element = (
<>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</> );
Benefits of JSX
Declarative Syntax: JSX makes it easier to visualize the UI structure directly in the code.
Dynamic Content: Embedding JavaScript expressions allows for dynamic rendering of data.
Cleaner Code: JSX reduces boilerplate code compared to manually using React.createElement().
Component:
React components are the fundamental building blocks of a React application.
They are independent, reusable pieces of code that represent different parts of a web page,
containing both structure and behavior.
It uses React elements and JSX to design its user interface.
React component is basically a JavaScript class (extends the React.component class) or pure
JavaScript function.
React component has properties, state management, life cycle and event handler.
React component can be able to do simple as well as advanced logic.
Components in React can be classified into two main types:
Functional Components
Class Components
Functional Components
Functional components are JavaScript functions that accept properties (props) and return a React
element.
They are simpler and more efficient compared to class components.
Here is an example of a functional component:
function Welcome()
{
return <h1>Hello, Welcome to CSD</h1>;
}
Functional components are ideal for presenting static UI elements or composing multiple simple
components together under a single parent component.
Class Components
Class components are more complex and can show inheritance and access data of other components.
They must include the line extends React.Component to pass data from one class component to another.
Here is an example of a class component:
class Welcome extends React.Component
{
render()
{
return <h1>Hello, Welcome to CSD</h1>;
}
}
Class components are generally less efficient compared to functional components and are recommended
to be used only when necessary
Rendering Components
Rendering components means turning your component code into the UI that users see on the screen.
React can render user-defined components by initializing an element with a component and passing it
to ReactDOM.render().
Here is an example:
import React from "react";
import ReactDOM from "react-dom";
React provides CLI tools for the developer to fast forward the creation, development and
deployment of the React based web application. React CLI tools depends on the Node.js and must be
installed in your system.
node --version
v14.2.0
Tool chain
To develop lightweight features such as form validation, model dialog, etc., React library can be directly
included into the web application through content delivery network (CDN).
It is similar to using jQuery library in a web application
For moderate to big application, it is advised to write the application as multiple files and then use
bundler such as webpack, parcel, rollup, etc., to compile and bundle the application before deploying the
code.
React toolchain helps to create, build, run and deploy the React application. React toolchain basically
provides a starter project template with all necessary code to bootstrap the application.
Let us create a simple static site and serve the application using serve app.
Open a command prompt and go to your workspace.
cd /go/to/your/workspace
Create a new folder, static_site and change directory to newly created folder.
mkdir static_site
cd static_site
Next, create a simple webpage inside the folder using your favorite html editor.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Static website</title>
</head>
<body>
<div>
<h1>Hello!</h1>
</div>
</body>
</html>
Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve
application will serve our webpage as shown below.
The serve will serve the application using default port, 5000. If it is not available, it will pick up a
random port and specify it.
Babel compiler
Babel is a JavaScript compiler which compiles many variant (es2015, es6, etc.,) of JavaScript into
standard JavaScript code supported by all browsers.
React uses JSX, an extension of JavaScript to design the user interface code.
Babel is used to compile the JSX code into JavaScript code.
To install Babel and it’s React companion, run the below command:
Create React App toolchain
Create React App is a modern CLI tool to create single page React application.
It is the standard tool supported by React community.
It handles babel compiler as well.
Let us install Create React App in our local system.
Building a product in ReactJS involves creating a structured and interactive user interface. Here's a concise
guide to help you get started:
Set Up Your Environment
Plan Your Product Structure
Build Components
Manage State
Style Your App
Add Routing
Fetch Data
Optimize and Deploy
Performance
React uses Virtual DOM concept to check and update the HTML document.
Virtual DOM is a special DOM created by React.
Virtual DOM represents the real DOM of the current document. Whenever there is a change in the
document, React checks the updated virtual DOM with the previous state of the Virtual DOM and
update only the different in th actual / real DOM.
This improves the performance of the rendering of the HTML document.
For example, if we create a React component to show the current time by periodically updating the
time through setInterval() method, then React will update only the current time instead of
updating the whole content of the component.
Easy to learn
The core concept of React can be learned in less than a day. React can be coded in either
Plain Javascript (ES6) or Typescript. To start with React, the basic knowledge of the
JavaScript is enough.
For advanced developer, Typescript provides type safety and rich language feature.
A react component can be created by a developer in few hours by learning JSX (similar to
HTML) and properties (props).
React provides simple lifecycle for its component, which can be used to properly setup and
destroy the component.
Large community
React developer community is a huge community with lot of activities.
React community is very active that you can get answer for any react related question / doubts in a
few minutes through google, stackoverflow, etc.,
SEO friendliness
React is one of the few JavaScript library to support SEO features. Since React components and
JSX are similar to HTML elements, SEO can be easily achieved without much code / setup.
Search Engine Optimization (SEO) is crucial for ensuring that your React applications are
discoverable by search engines like Google, Bing, and Yahoo.
React components are the fundamental building blocks of a React application.They are
independent, reusable pieces of code that represent different parts of a web page, containing both
structure and behavior.It uses React elements and JSX to design its user interface. React
component is basically a JavaScript class (extends the React.component class) or pure JavaScript
function.
React component has properties, state management, life cycle and event handler. React
component can be able to do simple as well as advanced logic.
Components in React can be classified into two main types:
Functional Components
Class Components
Functional Components
Functional components are JavaScript functions that accept properties (props) and return a React
element.
They are simpler and more efficient compared to class components.
Here is an example of a functional component:
function Welcome()
{
return <h1>Hello, Welcome to CSD</h1>;
}
Functional components are ideal for presenting static UI elements or composing multiple simple
components together under a single parent component.
Class Components
Class components are more complex and can show inheritance and access data of other
components.
They must include the line extends React.Component to pass data from one class component to
another.
Here is an example of a class component:
class Welcome extends React.Component
{
render()
{
return <h1>Hello, Welcome to CSD</h1>;
}
}
Class components are generally less efficient compared to functional components and are
recommended to be used only when necessary
Rendering Components
Rendering components means turning your component code into the UI that users see on the
screen.
React can render user-defined components by initializing an element with a component and
passing it to ReactDOM.render().
Here is an example:
import React from "react";
import ReactDOM from "react-dom";
Unit-II
1. Explain briefly about Breaking the app into components in Time logging Application with relevant
code.
Breaking a ReactJS time-logging app into components is essential for better organization, reusability,
and maintainability.
1. App Structure
Organize your app into logical components based on functionality. For a time-logging app, you
might have:
App Component: The root component managing the overall state.
TimeLogger Component: Handles the form for logging time.
LogList Component: Displays the list of logged times.
LogItem Component: Represents a single log entry.
Footer Component: Displays footer information or credits.
2. Component Breakdown
App Component
Purpose: Acts as the root component, managing global state (e.g., logs).
Responsibilities:
Store the list of logs in state.
Pass state and handlers as props to child components.
Header Component
Purpose: Displays the app's title or navigation.
Example:
function Header()
{
return <header><h1>Time Logging App</h1></header>;
}
export default Header;
TimeLogger Component
Purpose: Provides a form for users to log time.
Example:
LogList Component
Purpose: Displays a list of logged times.
Example:
Footer Component
Purpose: Displays footer information.
Example:
function Footer() {
return <footer><p>© 2025 Time Logging App</p></footer>;
}
export default Footer;
3. Folder Structure
Organize your files for clarity:
src/
├── components/
│ ├── Header.js
│ ├── TimeLogger.js
│ ├── LogList.js
│ ├── LogItem.js
│ ├── Footer.js
├── App.js
├── index.js
This modular approach ensures your app is clean, scalable, and easy to maintain!
To build a static version of your React app, you can follow these steps. This process involves
creating a production-ready build of your app that can be deployed as static files:
3.What is Stateful and Stateless Components in ReactJS. Explain with an example code.
In React, components can be categorized as stateful or stateless based on whether they manage
their own state or not. Here's a concise explanation:
Stateful Components
Definition: These components manage their own state using this.state (in class
components) or the useState hook (in functional components).
Purpose: They handle dynamic data and user interactions, maintaining information that can
change over time.
Stateless Components
Definition: These components do not manage state. They rely entirely on props passed
from parent components.
Purpose: They are used for rendering static or presentational content.
In React, a component should be stateful when it needs to manage or track data that changes over time and
directly affects the component's behavior or rendering.
Here are some scenarios where a stateful component is appropriate:
);
};
export default Counter;
In React, inverse data flow refers to the process of passing data from a child component to its parent.
Since React follows a unidirectional data flow (parent-to-child), inverse data flow is achieved
using callback functions.
Here's how you can implement it:
Steps to Implement Inverse Data Flow
Define a Callback Function in the Parent Component:
Create a function in the parent component that updates its state or performs
an action.
Pass this function as a prop to the child component.
Invoke the Callback in the Child Component:
Call the passed function from the child component, optionally passing data
as arguments.
Example: Time-Logging Application with Inverse Data Flow
Unit-III
Explanation:
State Management:
useState is used to track the number of seconds elapsed.
Effect Hook:
useEffect is used to set up the timer when the component mounts.
The setInterval function increments the seconds state every 1000 milliseconds (1
second).
The cleanup function (clearInterval) ensures the timer is stopped when the
component unmounts, preventing memory leaks.
Dependency Array:
The empty array [] ensures the useEffect runs only once when the component is
mounted.
Key Features:
Dynamic Input:
The user can input the countdown time in seconds.
Start/Stop/Reset:
Buttons allow the user to control the timer.
Effect Dependencies:
The useEffect hook listens to changes in isRunning and timeLeft to manage the
timer dynamically.
Key Features:
Timer Component:
Tracks elapsed time for a specific task.
Allows starting, pausing, resetting, and logging time.
Uses useEffect to update the timer every second when running.
Parent Component:
Manages a list of logged times.
Displays logs with task names, elapsed time, and timestamps.
Time Formatting:
Converts seconds into HH:MM:SS format for better readability.
Dynamic Task Support:
Multiple Timer components can be added for different tasks.
In React, managing timers (like those created with setTimeout or setInterval) is crucial to
avoid memory leaks or unexpected behavior, especially when components unmount or re-render.
Below is a guide on how to properly delete timers in React using hooks.
Explanation:
setTimeout: A timer is set to increment the count after 1 second.
Cleanup with clearTimeout: The return function inside useEffect ensures the timer is cleared
when the component unmounts or before the effect re-runs (e.g., when count changes).