[go: up one dir, main page]

0% found this document useful (0 votes)
9 views22 pages

REACT JS Mid-1 AssignmentQuestion&Answers-CSD

The document provides an overview of ReactJS, a JavaScript library for building user interfaces, detailing its applications, features, architecture, installation process, and advantages. It highlights the component-based architecture, virtual DOM for performance, and the use of JSX for easier coding. Additionally, it emphasizes React's large community support and the availability of numerous third-party components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views22 pages

REACT JS Mid-1 AssignmentQuestion&Answers-CSD

The document provides an overview of ReactJS, a JavaScript library for building user interfaces, detailing its applications, features, architecture, installation process, and advantages. It highlights the component-based architecture, virtual DOM for performance, and the use of JSX for easier coding. Additionally, it emphasizes React's large community support and the availability of numerous third-party components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Anil Neerukonda Institute of Technology

D & Sciences (Autonomous) (Affiliated to AU,


Approved by AICTE & Accredited by NBA & NAAC with A+ Grade) Sangivalasa-531 162,
Bheemunipatnam Mandal, Visakhapatnam District
Phone:08933-225083/84/87Fax:226395
Website:email:

Department of Computer Science & Engineering (Data Science)


Mid
Examination –
I

ReactJS - Assignment Questions (Answer any 10 Questions)

Unit-I

1.What is ReactJS? Explain briefly about Applications of ReacJS?

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.

2.What is Front-End Development? Differentiate between JavaScript and ReactJS.


Front-end Development is the development or creation of a user interface using some markup
languages and other tools. It is the development of the user side where only user interaction will be
counted. It consists of the interface where buttons, texts, alignments, etc are involved and used by the user.
JavaScript React.js

It is a Programming Language It is a JavaScript Library

General-purpose scripting for web development Specialized for building user interfaces (UIs) in
web apps

Browser (Client-side) and Server (Node.js) Browser (Client-side)

Syntax Plain JavaScript Syntax JSX (JavaScript XML)

Architecture of JavaScript is Event-driven Architecture of React.js is Component-based

Manually typed Supported (Context API, Redux, etc.)

Dependent on browser and implementation Optimized with virtual DOM

Broad ecosystem of libraries and frameworks Rich ecosystem with React-specific tools and
libraries

Developed by Netscape Communications Developed by Facebook


Corporation

Widely used across web and server environments Specifically for front-end UI development

3.Explain briefly about Features of ReactJS

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.

2. Virtual DOM for Fast Rendering

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.

4. Explain briefly about Architecture of ReactJS.


React’s primary purpose is to enable the developer to create user interface using pure JavaScript.
Normally, every user interface library introduces a new template language (which we need to learn) to design
the user interface and provides an option to write logic, either inside the template or separately.
Instead of introducing new template language, React introduces three simple concepts as given below:
 React elements
 JSX
 React component

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

Creating and Rendering React Elements


To create a React element, you can use JSX syntax, which looks similar to HTML.
For example:
const element = <h1>Hello, world!</h1>;

 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.

Key Features of JSX

 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";

const Welcome = () =>


{
return <h1>Hello World!</h1>;
};
ReactDOM.render(<Welcome />, document.getElementById("root"))
 The Welcome component is rendered to the DOM element with the id "root"
5.Explain briefly about Installation process of ReactJS.

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.

Some of the popular toolchain to develop React applications are:


 Create React App - SPA oriented toolchain
 Next.js - server-side rendering oriented toolchain
 Gatsby - Static content oriented toolchain

Tools required to develop a React application are:


 The serve, a static server to serve our application during development
 Babel compiler
 Create React App CLI

The serve static server


 The serve is a lightweight web server. It serves static site and single page application.
 It loads fast and consume minimum memory. It can be used to serve a React application.
 Let us install the tool using npm package manager in our system.
npm install serve -g

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, run the serve command


serve .
We can also serve single file, index.html instead of the whole folder.
serve ./index.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.

6.Explain briefly about Building product of ReactJS

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

7. Explain briefly about advantages of ReactJS.

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.

Huge collection of third party components


 In addition to core react library (which is only a few KB in size), React community provides a
large number of component for a wide range of application from simple UI component to full
fledged PDF Viewer component.
 React provides multiple option in each category. For example, the advanced state management can
be done using either Redux or MobX library. Redux and Mobx are just two popular library to do
state management. React has more than 10 library to archive the same functionality.
 Similarly, React community provides lot of third party library in each category like routing, data
grid, calendar, form programming, etc.,

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.

Easy kickstart of React project


 React provides a CLI application, create-react-app to create a new react application.
 A command line interface (CLI) is a computer program that runs on text-based inputs to execute
different tasks. Instead of pointing and clicking with a mouse, it receives single-line commands
that interact with system elements like file management.
 create-react-app application not only create a new application, it also build and run the application
in the local environment without any other dependencies.
 create-react-app allows the developer to choose a template, which allows the application to include
more boilerplate code during initial setup itself. This allows the developer to kickstart small
application to large application in few clicks.
 In addition to create-react-app, React community additional tools such as nextjs, gatsby, etc.,
which allows developer to create advanced application in a short period of time.

Rich set of developer tools


 React community provides essential developer tools to enhance the developer productivity.
 React developer tool for chrome, edge and firefox browser enables developer to select a react
component and see the current state of the component.
 Also, it enables the developer to has clear picture of the view of the component hierarchy by show
it as a tree of component in the Developer Tab of the browser.

Handle large application


 React uses composition to merge multiple component into one bigger component, which in turn
allows to create much more larger component.
 React component can be created in a single JavaScript file and can be set as exportable. This
feature allows multiple component to be grouped under a common category as module and can be
reused in other places.

8.What is a component. Explain its types with example code each.

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";

const Welcome = () =>


{
return <h1>Hello World!</h1>;
};
ReactDOM.render(<Welcome />, document.getElementById("root"))
 The Welcome component is rendered to the DOM element with the id "root"

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.

Here's a suggested structure and explanation:

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.

import React, { useState } from "react";


import Header from "./Header";
import TimeLogger from "./TimeLogger";
import LogList from "./LogList";
import Footer from "./Footer";
function App() {
const [logs, setLogs] = useState([]);
const addLog = (log) => setLogs([...logs, log]);
return (
<div>
<Header />
<TimeLogger onAddLog={addLog} />
<LogList logs={logs} />
<Footer />
</div> );
} export default App;

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:

import React, { useState } from "react";


function TimeLogger({ onAddLog }) {
const [task, setTask] = useState("");
const [time, setTime] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (task && time) {
onAddLog({ task, time, id: Date.now() });
setTask("");
setTime(""); }
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Task"
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<input
type="number“
placeholder="Time (hours)"
value={time}
onChange={(e) => setTime(e.target.value)}
/>
<button type="submit">Log Time</button>
</form>
);
} export default TimeLogger;

LogList Component
Purpose: Displays a list of logged times.
Example:

import LogItem from "./LogItem";


function LogList({ logs }) {
return (
<ul>
{logs.map((log) => (
<LogItem key={log.id} log={log} />
))}
</ul> );
} export default LogList;

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!

2. How to build static version of the app in ReactJS.

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:

1. Prepare Your React App


Ensure your app is ready for production:
 Remove unnecessary files or components.
 Test your app thoroughly in development mode (npm start or yarn start).

2. Build the Static Files


Run the following command in your project directory:
npm run build
This will create a build/ directory containing the static files (HTML, CSS, JS, etc.)
optimized for production.
3. Serve or Deploy the Static Files
You can now serve or deploy the static files using various methods:

Option 1: Serve Locally


To test the static build locally, use a simple HTTP server like serve
npx serve -s build
This will serve your app at http://localhost:5000 by default.

Option 2: Deploy to a Static Hosting Service


You can deploy the build/ directory to any static hosting service, such as:
 Netlify: Drag and drop the build/ folder into the Netlify dashboard.
 Vercel: Use the Vercel CLI or dashboard to deploy.
 GitHub Pages: Use the gh-pages package to deploy.
 Firebase Hosting: Use Firebase CLI to deploy.

4. Verify the Deployment


Once deployed, visit your app's URL to ensure everything works as expected.

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:

1. Managing User Input


 Components that handle forms, text inputs, or any user interaction where the input needs to
be tracked.
 Example: A login form that tracks the username and password fields.
2. Tracking UI State
 Components that manage UI elements like modals, dropdowns, or toggles.
 Example: A modal component that tracks whether it is open or closed.
3. Fetching and Storing Data
 Components that fetch data from APIs and store it locally for rendering.
 Example: A dashboard component that fetches and displays user statistics.
4. Handling Application Logic
 Components that manage complex logic, such as filtering, sorting, or pagination.
 Example: A product list component that tracks the current page and applied filters.
5. Parent Components Passing Props
 Components that act as containers, managing state and passing it down as props to child
components.
 Example: A shopping cart component that tracks selected items and passes them to a
stateless cart summary component.
//Stateful Components //Stateless Components
import React, { useState } from 'react'; const Greeting = ({ name }) => {
const Counter = () => { return <h1>Hello, {name}!</h1>;
const [count, setCount] = useState(0); };
return ( export default Greeting;
<div>
<p>Count: {count}</p>

<button onClick={() => setCount(count +


1)}>Increment</button>
</div>

);
};
export default Counter;

3. Write code for stateful components in react js time-logging application

import React, { useState } from "react";


const TimeLogger = () => {
const [startTime, setStartTime] = useState(null);
const [endTime, setEndTime] = useState(null);
const [log, setLog] = useState([]);
const handleStart = () => {
const now = new Date();
setStartTime(now);
setEndTime(null); };
const handleStop = () => {
const now = new Date();
if (startTime) {
setEndTime(now);
setLog((prevLog) => [
...prevLog,
{ start: startTime.toLocaleTimeString(), end: now.toLocaleTimeString()
},
]);
setStartTime(null);
}
};
return (
<div style={{ padding: "20px", fontFamily: "Arial" }}>
<h2>Time Logging Application</h2>
<button onClick={handleStart} disabled={startTime}> Start Task </button> <button
onClick={handleStop} disabled={!startTime}> Stop Task </button>
<div style={{ marginTop: "20px" }}>
<h3>Logs:</h3>
{log.length === 0 ? (
<p>No logs yet.</p>
):(
<ul>
{log.map((entry, index) => (
<li key={index}> Task started at {entry.start} and ended at {entry.end}. </li>
))}
</ul> )}
</div>
</div>
);
}; export default TimeLogger;

4. Explain briefly about Hard-code initial states.


To hard-code initial states in ReactJS, you can directly define the initial state values within
the useState hook.
To hard-code initial states in a ReactJS time-logging app, you can define the initial state directly
within your component or use a state management library like Redux. Below is an example of how
to hard-code initial states using React's useState or useReducer hooks.

import React, { useState } from "react";


const TimeLoggingApp = () => {
const [tasks, setTasks] = useState([
{ id: 1, name: "Morning Meeting", duration: "1 hour" },
{ id: 2, name: "Code Review", duration: "2 hours" },
{ id: 3, name: "Development", duration: "3 hours" },
]);
return (
<div>
<h1>Time Logging App</h1>
<ul>
{tasks.map((task) => (
<li key={task.id}>
{task.name} - {task.duration}
</li>
)
)
}
</ul>
</div>
);
}; export default TimeLoggingApp;

6. Explain briefly about Add inverse data flow.

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

1. Parent Component (App.js)


The parent component will manage the state and pass a callback function to the child to
handle updates.

import React, { useState } from "react";


import TimeLogger from "./TimeLogger";
const App = () => {
const [logs, setLogs] = useState([]); // Callback to update logs const handleLogUpdate = (newLog) => {
setLogs((prevLogs) => [...prevLogs, newLog]);
};
return (
<div>
<h1>Time-Logging Application</h1>
<TimeLogger onLogUpdate={handleLogUpdate} />
<h2>Logs:</h2>
<ul> {logs.map((log, index) => ( <li key={index}>{log}</li>
)
)
}
</ul>
</div>
);
};
export default App;

2. Child Component (TimeLogger.js)


The child component will send data back to the parent using the callback function.

import React, { useState } from "react";


const TimeLogger = ({ onLogUpdate }) => {
const [task, setTask] = useState("");
const [timeSpent, setTimeSpent] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (task && timeSpent) {
const log = `Task: ${task}, Time Spent: ${timeSpent} hours`;
onLogUpdate(log); // Send data to parent
setTask("");
setTimeSpent("");
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Task Name" value={task} onChange={(e) => setTask(e.target.value)} />
<input type="number" placeholder="Time Spent (hours)" value={timeSpent} onChange={(e) =>
setTimeSpent(e.target.value)} />
<button type="submit">Log Time</button> </form>
);
};
export default TimeLogger;

Unit-III

1. Discuss about Updating timers in ReactJS.


To update timers in ReactJS, you can use the useEffect hook along with setInterval to
manage the timer's lifecycle.

Example: Timer Component in ReactJS

import React, { useState, useEffect } from "react";


const Timer = () => {
const [seconds, setSeconds] = useState(0); // State to track elapsed time useEffect(() => {
// Start the timer when the component mounts
const interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1); // Increment seconds
}, 1000);
// Cleanup function to clear the interval when the component unmounts
return () => {
clearInterval(interval); }; }, []); // Empty dependency array ensures this runs only once return
(
<div>
<h1>Timer: {seconds} seconds</h1> </div> );
};
export default Timer;

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.

Example: Countdown Timer with User Input

import React, { useState, useEffect } from "react";


const CountdownTimer = () => {
const [timeLeft, setTimeLeft] = useState(0); // State to track remaining time const [isRunning,
setIsRunning] = useState(false); // State to track if the timer is running
useEffect(() => {
let timer;
if (isRunning && timeLeft > 0) {
timer = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1); // Decrement time
}, 1000); } // Cleanup function to clear the interval
return () => {
clearInterval(timer);
};
}, [isRunning, timeLeft]); // Re-run effect when isRunning or timeLeft changes
const startTimer = () => {
if (timeLeft > 0) {
setIsRunning(true);
}
};
const stopTimer = () => {
setIsRunning(false);
};
const resetTimer = () => {
setIsRunning(false);
setTimeLeft(0);
};
return (
<div>
<h1>Countdown Timer: {timeLeft} seconds</h1>
<input type="number“
placeholder="Enter time in seconds"
onChange={(e) => setTimeLeft(Number(e.target.value))}
disabled={isRunning}
/>
<button onClick={startTimer} disabled={isRunning || timeLeft <= 0}> Start
</button>
<button onClick={stopTimer} disabled={!isRunning}> Stop </button>
<button onClick={resetTimer}>Reset</button>
</div> );
};
export default CountdownTimer;

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.

2. Write code for Updating timers in time-logging application

Example: Timer Component for Time Logging App

import React, { useState, useEffect } from "react";


const Timer = ({ taskName, onLogTime }) => {
const [elapsedTime, setElapsedTime] = useState(0); // Time in seconds
const [isRunning, setIsRunning] = useState(false); // Start or stop the timer
const toggleTimer = () => {
setIsRunning((prev) => !prev); }; // Reset the timer
const resetTimer = () => {
setElapsedTime(0);
setIsRunning(false);
}; // Log the time and reset
const logTime = () => {
onLogTime(taskName, elapsedTime); // Pass the task name and elapsed time to the parent
resetTimer(); }; // Update the timer every second when running
useEffect(() => {
let timerId;
if (isRunning) {
timerId = setInterval(() => {
setElapsedTime((prev) => prev + 1); }, 1000);
}
return () => clearInterval(timerId); // Cleanup on unmount or when isRunning changes
}, [isRunning]); // Format time in HH:MM:SS
const formatTime = (seconds) => {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60
const secs = seconds % 60;
return `${hrs.toString().padStart(2, "0")}:${mins .toString() .padStart(2, "0")}:$
{secs.toString().padStart(2, "0")}`; };
return (
<div style={{ marginBottom: "20px" }}>
<h3>Task: {taskName}</h3>
<p>Elapsed Time: {formatTime(elapsedTime)}</p>
<button onClick={toggleTimer}> {isRunning ? "Pause" : "Start"} </button> <button
onClick={resetTimer} disabled={!isRunning && elapsedTime === 0}> Reset </button>
<button onClick={logTime} disabled={elapsedTime === 0}> Log Time </button> </div> );
};
const TimeLoggingApp = () => {
const [logs, setLogs] = useState([]); // Handle logging time for a task
const handleLogTime = (taskName, time) => {
setLogs((prevLogs) => [ ...prevLogs, { taskName, time, loggedAt: new
Date().toLocaleString() }, ]);
};
return (
<div>
<h1>Time Logging App</h1>
<Timer taskName="Task 1" onLogTime={handleLogTime} />
<Timer taskName="Task 2" onLogTime={handleLogTime} />
<h2>Logged Times</h2>
<ul> {logs.map((log, index) => ( <li key={index}> Task: {log.taskName}, Time: {log.time}s,
Logged At: {log.loggedAt} </li> ))}
</ul>
</div>
);
};
export default TimeLoggingApp;

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.

3. Discuss about Deleting timers in ReactJS.

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.

Example: Clearing a Timer with setTimeout

import React, { useEffect, useState } from "react";


function TimerComponent() {
const [count, setCount] = useState(0);
useEffect(() => { // Set up a timer
const timer = setTimeout(() => {
setCount((prevCount) => prevCount + 1); }, 1000); // Cleanup function to clear the timer
return () => {
clearTimeout(timer);
};
}, [count]); // Dependency array ensures the timer resets when `count` changes return (
<div>
<h1>Count: {count}</h1>
</div> );
}
export default TimerComponent;

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).

4. Write code for Deleting timers in time-logging application

Managing and Deleting Timers

import React, { useState, useEffect } from "react";


const TimerComponent = () => {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
let timerId = null; // Timer ID for reference
// Start the timer
const startTimer = () => {
if (!isRunning) {
setIsRunning(true);
timerId = setInterval(() => {
setTime((prevTime) => prevTime + 1); }, 1000); // Increment time every second
}
}; // Stop the timer
const stopTimer = () => {
setIsRunning(false);
clearInterval(timerId); // Clear the interval
}; // Reset the timer
const resetTimer = () => {
stopTimer();
setTime(0); }; // Cleanup timer on component
unmount useEffect(() => {
return () => {
clearInterval(timerId); // Ensure timer is cleared }; }, []);
return (
<div>
<h1>Time: {time}s</h1>
<button onClick={startTimer} disabled={isRunning}> Start </button>
<button onClick={stopTimer} disabled={!isRunning}> Stop </button>
<button onClick={resetTimer}>Reset</button>
</div> );
};
export default TimerComponent;

You might also like