0% found this document useful (0 votes)
5 views24 pages

Unit 5

The document provides an overview of ReactJS, including its components, state management, and the differences between class and functional components. It also compares ReactJS with Angular, discusses the advantages of using React, and explains key concepts such as virtual DOM and single-page applications. Additionally, it includes code examples for implementing class and functional components, as well as differences between local and global scope, and between useState and useEffect hooks.

Uploaded by

ayanofficial0012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views24 pages

Unit 5

The document provides an overview of ReactJS, including its components, state management, and the differences between class and functional components. It also compares ReactJS with Angular, discusses the advantages of using React, and explains key concepts such as virtual DOM and single-page applications. Additionally, it includes code examples for implementing class and functional components, as well as differences between local and global scope, and between useState and useEffect hooks.

Uploaded by

ayanofficial0012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Full Stack Development

Unit 5
(2 marks)
1. What is reactjs?
React.js, commonly referred to as React, is an open-source JavaScript library
used for building user interfaces or UI components. It is maintained by
Facebook and a community of individual developers and companies. React is
particularly well-suited for developing single-page applications (SPAs) where
the user interface needs to be highly dynamic and responsive.
2. What is ES6?
ECMAScript 6 (ES6), also known as ECMAScript 2015, is the sixth edition of the
ECMAScript standard. ECMAScript is the scripting language specification upon
which JavaScript is based. ES6 was a significant update to the language and
brought many new features and enhancements to JavaScript.
3. What is the meaning of render in ReactJs?
In ReactJS, the term "render" has a specific meaning related to the rendering of
UI components. The render method is a fundamental part of a React
component. When you create a React component, you define a render method
that specifies what should be displayed on the screen.
4. What is a fragment in ReactJs?
In ReactJS, a fragment is a way to group multiple children elements without
introducing an additional DOM element. Fragments were introduced in React
16.2 to provide a cleaner and more concise syntax for returning multiple
elements from a component's render method.
5. What is a component in Reactjs?
In ReactJS, a component is a reusable, self-contained piece of code that
represents a part of the user interface (UI). Components are the building blocks
of a React application, and they encapsulate the logic and presentation of a
particular piece of the UI. React follows a component-based architecture,
allowing developers to create modular and reusable UI elements.
6. What are props in ReactJs?
In ReactJS, "props" is a shorthand term for "properties," and it refers to the
mechanism for passing data from a parent component to a child component.
Props are a way to communicate and share information between different
parts of a React application.
7. What is a state in ReactJs?
In ReactJS, "state" is a JavaScript object that represents the current condition
or data of a component. The state allows a React component to manage and
keep track of dynamic information that can change over time during the
component's lifecycle.
8. What are events in ReactJs?
In ReactJS, events are interactions or occurrences that happen in the user
interface, such as clicking a button, submitting a form, or hovering over an
element. React allows you to handle these events using special syntax and
methods, enabling you to create interactive and dynamic user interfaces.
9. What is a class component?
In ReactJS, a class component is a type of component that is defined using ES6
class syntax and extends the React.Component class. Class components are
also sometimes referred to as stateful components because they can have
state, which allows them to manage dynamic data and respond to changes in
the application.
10. What is a functional component?
In ReactJS, a functional component is a simpler and more concise way to define
a component using JavaScript functions. Functional components are also
known as stateless components because they don't have their own internal
state or lifecycle methods. They receive data via props and return React
elements to describe what should be rendered on the screen.
11. What is react-router-dom in ReactJs?
react-router-dom is a library for handling routing in React applications. It
provides a set of components that enable the navigation and management of
different views or pages within a React application. The library is part of the
react-router ecosystem, and react-router-dom is specifically designed for web
applications.
12. What is axios in React?
Axios is a popular JavaScript library for making HTTP requests in browsers and
Node.js environments. It is often used in React applications to interact with
APIs and fetch data from a server. Axios simplifies the process of sending
asynchronous HTTP requests and handling responses.
13. Why Reactjs is used?
ReactJS is a popular JavaScript library for building user interfaces, and it is
widely used for several reasons:
1. Declarative Syntax:
 React uses a declarative syntax, making it more intuitive and easier
to understand.
2. Component-Based Architecture:
 React follows a component-based architecture, allowing
developers to break down the UI into reusable and modular
components.
3. Virtual DOM:
 React utilizes a virtual DOM, a lightweight copy of the actual DOM.
4. Unidirectional Data Flow:
 React enforces a unidirectional data flow, which means that data
flows in one direction—from parent components to child
components.
14. How does Reactjswork?
React works by employing a virtual DOM (Document Object Model) and a
process known as reconciliation to efficiently update the actual DOM based on
changes in data or state. The following steps provide a high-level overview of
how React works:
1. Component Hierarchy:
 React applications are structured as a hierarchy of components.
2. Component Rendering:
 When a React application starts, the top-level component is
rendered into the virtual DOM.
3. Virtual DOM Creation:
 React creates a virtual representation of the DOM, which is a
lightweight in-memory copy of the actual DOM.
4. Initial Rendering:
 The initial rendering involves creating React elements for each
component and converting them into corresponding nodes in the
virtual DOM.

15. What are the advantages of Reactjs?


ReactJS, a popular JavaScript library for building user interfaces, offers several
advantages that contribute to its widespread adoption and popularity among
developers. Some of the key advantages of ReactJS include:
1. Declarative Syntax:
 React uses a declarative syntax, making it easier to understand and
reason about the application's UI.
2. Component-Based Architecture:
 React follows a component-based architecture, allowing
developers to break down the UI into modular and reusable
components.
3. Virtual DOM:
 React introduces a virtual DOM, which is a lightweight copy of the
actual DOM.
4. Performance Optimization:
 React's virtual DOM and diffing algorithm result in optimized
updates to the DOM.
16. What is single page application?
A Single Page Application (SPA) is a type of web application or website that
operates within a single HTML page. Unlike traditional multi-page applications,
SPAs dynamically update the content on the existing page in response to user
interactions, instead of loading entirely new pages from the server. The goal of
SPAs is to provide a more seamless and responsive user experience by reducing
the need for full-page reloads.
17. What is virtual dom in Reactjs?
The Virtual DOM (Document Object Model) is a key concept in ReactJS, and it is
a lightweight, in-memory representation of the actual DOM elements in a web
application. React uses the Virtual DOM to optimize and efficiently update the
UI, minimizing the need to directly manipulate the real DOM.
18. What is React Native?
React Native is an open-source framework developed by Facebook for building
mobile applications using JavaScript and React. It allows developers to use
React, a popular JavaScript library for building user interfaces, to create native
mobile applications for iOS and Android platforms. React Native enables the
development of cross-platform mobile apps that share a significant portion of
the codebase, while still delivering a native-like user experience.
19. What is the default port for Reactjs?
The default port for a ReactJS application when you run it locally during
development is usually port 3000. When you start a React application using
tools like Create React App or when you run it with the npm start command,
the development server typically uses port 3000 by default.
20. What is software requirements and commands to create a Reactjs project?
Software Requirements for Creating a ReactJS Project:
Before creating a ReactJS project, ensure that you have the following software
installed on your computer:
1. Node.js:
React relies on Node.js for package management and running
scripts. You can download and install Node.js from the official
website: Node.js
2. npm (Node Package Manager):
 npm is included with Node.js and is used to manage packages
(libraries and tools) in your React project.
Commands to Create a ReactJS Project:
To create a new ReactJS project, you can use a tool called Create React App,
which is an officially supported way to create single-page React applications.
Here are the steps:
1. Open a Terminal or Command Prompt:
 Open your terminal or command prompt where you want to
create your React project.
2. Install Create React App:
 Run the following command to install Create React App globally on
your machine:
npm install -g create-react-app

(5 marks)
21. What is the difference between real DOM and virtual DOM?
Real DOM Virtual DOM

Real DOM represent actual Virtual DOM represent the virtual/memory


structure of the webpage. representation of the Webpage.

DOM manipulation is very


DOM manipulation is very easy
expensive

There is too much memory


No memory wastage
wastage

It updates Slow It updates fast

It can directly update HTML It can’t update HTML directly

Creates a new DOM if the


Update the JSX if the element update
element updates.
Real DOM Virtual DOM

It allows us to directly target It can produce about 200,000 Virtual


any specific DOM
node (HTML element) Nodes / Second.

It represents the Ul of your It is only a virtual representation of the


application DOM

22. What is the difference between class components and functional components?
Class
Functional Components Components

A functional component is just a A class component requires you to


plain JavaScript pure function that extend from React. Component and
accepts props as an argument and create a render function that returns
returns a React element(JSX). a React element.

It must have the render() method


There is no render method used in
returning JSX (which is syntactically
functional components.
similar to HTML)

The class component is instantiated


Functional components run from top and different life cycle method is
to bottom and once the function is kept alive and is run and invoked
returned it can’t be kept alive. depending on the phase of the class
component.

Also known as Stateless


components as they simply accept Also known as Stateful components
data and display them in some form, because they implement logic and
they are mainly responsible for state.
rendering UI.
React lifecycle methods (for
React lifecycle methods can be used
example, componentDidMount)
inside class components (for
cannot be used in functional
example, componentDidMount).
components.

It requires different syntax inside a


Hooks can be easily used in class component to implement
functional components to make hooks.
them Stateful. Example:
Example: constructor(props) {
const [name,SetName]= super(props);
React.useState(' ') this.state = {name: ' '}
}

Constructor is used as it needs to


Constructors are not used.
store state.

23. What is the difference between Angular and Reactjs?

Angular React

Type Full-fledged structural JavaScript-based library


framework

Purpose Develop dynamic web Build interactive UI components


apps

Language TypeScript JavaScript (JSX script)

Developed and Google Meta and community


maintained by
Front-end Extends the functionality Uses XML-like syntax called JSX,
development of HTML, prefers client- slight preference for server-side
approach side rendering rendering

DOM Real Virtual

Performance High Relatively high (since virtual


DOM renders updates much
faster & ensures fast runtime
performance)

Dynamic UI UI binding at plain object Direct linking of states to the UI


binding or property level

App structure Fixed and complex Flexible, component-based


platform, component-
based framework

Data binding Two-way One-way

Dependency Supports dependency Does not fully enable


injection injection, allowing for dependency injection, because
separate lifecycles for each component has its own
different stores global state

Learning curve Can be steep for Relatively small


beginners
GitHub stars 86.7k 203k

Ideal use cases Develop complex Modern and large web apps with
enterprise apps, frequently variable data, natively-
progressive and single- rendered hybrid apps for Android
page web apps and and iOS devices
websites

24. Write a program and implement class component in it?


import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleIncrement = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
render() {
return (
<div>
<h2>Counter: {this.state.count}</h2>
{/* Button to trigger the handleIncrement method */}
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default Counter;
25. Write a program and implement functional component in it?
import React, { useState } from 'react';
React Hooks
function FunctionalCounter() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
<h2>Functional Counter: {count}</h2>
{/* Button to trigger the handleIncrement function */}
<button onClick={handleIncrement}>Increment</button>
</div>
);
}
export default FunctionalCounter;
26. What is the difference between local scope and global scope?
Key Differences:
 Visibility:
 Local scope variables are visible only within the block in which
they are declared.
 Global scope variables are visible throughout the entire program.
 Access:
 Local scope variables are accessed only within the function or
block in which they are defined.
 Global scope variables can be accessed from any part of the code.
 Lifetime:
 Local scope variables have a limited lifetime, existing only as long
as the function or block is executing.
 Global scope variables persist for the entire duration of the
program.
 Avoiding Conflicts:
 Local scope helps avoid naming conflicts since variables with the
same name can exist in different functions without interfering with
each other.
 Global scope requires careful naming to avoid unintentional
conflicts, especially in large codebases.
 Example:
 function myFunction() {
let localVar = "I am local";
console.log(localVar);
if (true) {
let innerVar = "I am also local";
console.log(innerVar);
}
console.log(innerVar);
}

myFunction();
 let globalVar = "I am global";

function myFunction() {
console.log(globalVar);
}
console.log(globalVar);
myFunction();
27. What is the difference between useState Hook and useEffect Hook? Key
Differences:
 State vs. Side Effects:
 useState: Manages state within functional components.
 useEffect: Handles side effects like data fetching, subscriptions,
etc.
 Return Value:
 useState: Returns an array with the current state value and a
function to update the state.
 useEffect: Does not return anything. If cleanup is needed, it can
return a cleanup function.
 Purpose:
 useState: Primarily used for managing local component state.
 useEffect: Primarily used for handling side effects after the
component has rendered.
 Execution Timing:
 useState: Executed synchronously during the component render.
 useEffect: Executed asynchronously after the component has
rendered.
 Dependencies:
 useState: Does not have dependencies.
 useEffect: Can have an optional dependency array to control when
the effect runs.

28. Why we use Reactjs instead of other frameworks like Angular?


Parameters Angular React
Developed By Google Facebook
Parameters Angular React
Release Year 2009 2013
Written In TypeScript JavaScript
JavaScript library (View in MVC;
Technology Full-fledged MVC framework
requires Flux to implement
Type written in JavaScript
architecture)
Brings JavaScript into HTML Brings HTML into JavaScript
Concept Works with the real DOM Client- Works with the virtual DOM
side rendering Server-side rendering
Data Binding Two-way data binding One-way data binding
Language JavaScript + HTML JavaScript + JSX
Learning Curve Steep Moderate
UI Rendering Client/Server-Side Client/Server-Side
Highly active and interactive Larger apps with recurrent
Best Suited For
web apps variable data
App Structure Fixes and complicated MVC Flexible component-based view
Dependency
Fully supported Not supported
Injection
Performance High High
DOM Type Real Virtual
Facebook, Skype, Instagram,
Popular Apps IBM, PayPal, Freelancer, Upwork
Walmart
generally recommended for better predictability and
maintainability.

(10 Marks)
29. A Part:-What are reactjs forms? B Part:- write a program and implement
functional component based form in it?
A. ReactJS Forms:
In ReactJS, forms are used to handle user input and allow users to interact with
the application by entering data, making selections, and submitting
information. React provides a declarative way to manage and handle forms
using controlled components, where form elements are controlled by the state
of the React components. This allows React to manage the state of the form
elements and update the UI in response to user input.
B. Implementing a Functional Component-Based Form:
import React, { useState } from 'react';
function FunctionalForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
});
const handleInputChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted Data:\nUsername: ${formData.username}\nEmail:
${formData.email}`);
};
return (
<div>
<h2>Functional Component Form Example</h2>
<form onSubmit={handleSubmit}>
{/* Username input */}
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleInputChange}
required
/>
</label>
<br />
{/* Email input */}
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
required
/>
</label>
<br />
{/* Submit button */}
<button type="submit">Submit</button>
</form>
</div>
);
}
export default FunctionalForm;
30. A Part:-What is MySql?B Part:-Write a program to implement the connectivity of
Reactjs with Mysql?
A. What is MySQL?
MySQL is an open-source relational database management system (RDBMS)
that is widely used for managing and organizing data in a structured format. It
is a popular choice for web applications, providing a robust, scalable, and
efficient solution for storing and retrieving data. MySQL supports SQL
(Structured Query Language) for defining and manipulating the database, and
it is known for its reliability, performance, and ease of use.
B. Connecting ReactJS with MySQL:
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
const connection = mysql.createConnection({
host: 'your_mysql_host',
user: 'your_mysql_user',
password: 'your_mysql_password',
database: 'your_mysql_database',
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ', err);
} else {
console.log('Connected to MySQL!');
}
});
app.use(cors());
app.use(bodyParser.json());
app.get('/api/data', (req, res) => {
const sql = 'SELECT * FROM your_table_name';
connection.query(sql, (err, results) => {
if (err) {
console.error('Error executing MySQL query: ', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.json(results);
}
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
31. A Part:-What are components in Reactjs ?B Part:- How many ways we can create
react components in Reactjs?
A. Components in ReactJS:
In ReactJS, a component is a reusable, self-contained building block that
encapsulates a piece of UI and its behavior. Components allow you to break
down the user interface into modular and manageable parts, making the code
more organized, scalable, and easier to maintain. React applications are
typically composed of multiple components that work together to create a
complete UI.
There are two main types of components in React:
1. Functional Components:
 Also known as stateless or presentational components.
 Defined as JavaScript functions that take props as an argument
and return React elements.
 Best suited for simple components that don't need to manage
state or lifecycle methods.
 Introduced in React 16.8 with the addition of Hooks, which allow
functional components to manage state and use lifecycle
methods.
function MyFunctionalComponent(props) {
return <div>Hello, {props.name}!</div>;
}
2. Class Components:
 Also known as stateful or container components.
 Defined as ES6 classes that extend React.Component class.
 Can manage local state, use lifecycle methods, and handle more complex
logic.
 Used in older React versions and is still relevant, but functional
components with Hooks are more commonly used in modern React
development.
class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render() {
return <div>Count: {this.state.count}</div>;
}
}
B. Ways to Create React Components:
There are several ways to create React components:
1. Function Declaration:
 Using a regular function to declare a functional component.
function MyFunctionalComponent() {
return <div>Hello, World!</div>;
}
2. Function Expression:
 Using a function expression to declare a functional component.
const MyFunctionalComponent = function() {
return <div>Hello, World!</div>;
};
3. Arrow Function:
 Using an arrow function to declare a functional component.
const MyFunctionalComponent = () => {
return <div>Hello, World!</div>;
};
4. Class Declaration:
 Using the class keyword to declare a class component.
class MyClassComponent extends React.Component {
render() {
return <div>Hello, World!</div>;
}
}
5. Class Expression:
 Using a class expression to declare a class component.
const MyClassComponent = class extends React.Component {
render() {
return <div>Hello, World!</div>;
}
};
32. A Part: -What is the difference between state and props in Reactjs? B Part: -
Write a program to create home, about page?

PROPS STATE

The Data is passed from one The Data is passed within the component
component to another. only.

It is Immutable (cannot be
It is Mutable ( can be modified).
modified).

Props can be used with state The state can be used only with the state
and functional components. components/class component (Before 16.0).
PROPS STATE

Props are read-only. The state is both read and write.

// Home.js
import React from 'react';
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the Home Page!</p>
</div>
);
}
export default Home;
// About.js
import React from 'react';
function About() {
return (
<div>
<h2>About Page</h2>
<p>This is the About Page.</p>
</div>
);
}
export default About;
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>

<hr />

<Route exact path="/" component={Home} />


<Route path="/about" component={About} />
</div>
</Router>
);
}
export default App;
33. Explain the life cycle methods of a Reactjs component?
React components go through a lifecycle during which they are created,
updated, and eventually destroyed. These lifecycle methods provide
developers with the ability to run code at specific points in the component's
existence. In React, there are three main phases in the lifecycle of a
component:
1. Mounting:
 This phase occurs when an instance of a component is being
created and inserted into the DOM.
 constructor(props):
 The constructor is called before a component is mounted.
 It is used to initialize state, bind event handlers, and
perform other setup tasks.
 static getDerivedStateFromProps(props, state):
 This method is called right before rendering when new
props or state are received.
 It returns an object to update the state or null to indicate no
state update is necessary.
 render():
 The render method is responsible for returning the JSX that
represents the component's UI.
 It must be a pure function without side effects.
 componentDidMount():
 This method is called after the component has been
rendered to the DOM.
 It is often used for making network requests or initializing
subscriptions.
2. Updating:
This phase occurs when a component is being re-rendered as a
result of changes to either its props or state.
 static getDerivedStateFromProps(nextProps, nextState):
 Similar to the mounting phase, this method is called before
rendering when new props or state are received.
 It returns an object to update the state or null to indicate no
state update is necessary.
 shouldComponentUpdate(nextProps, nextState):
 This method is called before rendering when new props or
state are received.
 It allows you to control whether the component should re-
render by returning a boolean value.
 It can be used to optimize performance by preventing
unnecessary renders.
 render():
 The render method is called to update the UI with the latest
props and state.
 getSnapshotBeforeUpdate(prevProps, prevState):
 This method is called right before the changes from render
are committed to the DOM.
 It receives the previous props and state and can return a
value that will be passed to componentDidUpdate.
 componentDidUpdate(prevProps, prevState, snapshot):
 This method is called after the component has been
updated and the changes are committed to the DOM.
 It is often used for interactions with the DOM or side effects
based on the updated state.
3. Unmounting:
 This phase occurs when a component is being removed from the
DOM.
 componentWillUnmount ():
 This method is called just before the component is
unmounted and destroyed.
 It is used for cleanup tasks such as canceling network
requests, clearing subscriptions, or cleaning up timers.

34. 6.How do you create a React App? Explain Steps to Create a React App in detail.
1. Install Create React App:
 Open your terminal or command prompt.
 Run the following command to install Create React App globally on
your machine:
npm install -g create-react-app
2. Create a New React App:
 Run the following command to create a new React app. Replace
my-react-app with the desired name of your project:
npx create-react-app my-react-app
 The npx command is used to run Create React App without the
need to globally install it.
3. Navigate to the Project Directory:
 Move into the newly created project directory:
cd my-react-app
4. Start the Development Server:
 Run the following command to start the development server:
npm start
 This will launch the development server, and you should see your
React app running in your default web browser.
5. Explore Your React App:
 Open your web browser and go to http://localhost:3000 to view
your React app.
 You can now start editing the src files to customize your app. Any
changes you make will automatically be reflected in the browser.
35. What are forms in Reactjs? Explain in detail.
In React, forms are used to collect and handle user input. They allow users to
interact with the application by entering data, making selections, and
submitting information. React provides a way to manage and handle forms, and
it includes features to make form development more controlled and efficient.
Key concepts related to forms in React:
1. Controlled Components:
 In React, form elements like input fields, text areas, and select
dropdowns are typically controlled components. This means that
their value is controlled by the state in the React component, and
any changes to the input are handled by updating the
component's state.
2. State Management:
 The state of a form in React is often managed using the useState
hook. The value of form elements is stored in the component's
state, and updating the state triggers re-rendering of the
component.
3. Event Handling:
 React uses synthetic events to handle user interactions with form
elements. Event handlers, such as onChange for input changes and
onSubmit for form submissions, are used to respond to user
actions.
4. Uncontrolled Components:
 While controlled components are the typical approach in React,
uncontrolled components (where the form elements manage their
own state) are also possible. However, controlled components are

36. React Router for Navigation


Implement navigation between different pages in a React app using React
Router.
 Create a simple app with three pages: Home, About, and Contact.
 Use React Router's Route and Link components to navigate between the
pages.
 Ensure that the pages are rendered without reloading the page.

You might also like