Lecture Notes Of Day 2: Setting Up React Environment
Objective:
The goal of this class is
to set up the React development environment on your local machine using
Node.js, npm, and Create React App. By the end of this class, you will have
installed all the necessary tools, created your first React project, and run it
locally on your computer.
Outcome:
- Install
Node.js and npm (Node Package Manager).
- Install
Create React App to create React projects easily.
- Set
up a simple React project.
- Run
the React application locally.
Introduction to React
Development Environment
Before diving into
building React applications, it’s important to have the proper environment set
up. React is a JavaScript library that runs on your browser, and it needs a
development environment to write, test, and run your code.
What is React?
- React
is a JavaScript library for building user interfaces.
- React
allows developers to create large web applications that can change data,
without reloading the page.
- React
is component-based, meaning that the UI is divided into independent,
reusable pieces.
What is Create React App?
- Create
React App is a tool that sets up a new React project with a pre-configured
development environment.
- It
installs all the required packages and configurations automatically, so
developers don’t need to manually set up Webpack, Babel, or other build
tools.
Step 1: Installing
Node.js and npm
React relies on Node.js
and npm (Node Package Manager) to manage dependencies (packages or libraries)
and run the application.
1.
Install Node.js and npm:
o Node.js is
a JavaScript runtime used to run React and other JavaScript applications.
o npm
is the Node.js package manager that helps manage libraries and dependencies for
your projects.
How to install:
o Go
to the official Node.js website.
o Download
the recommended LTS (Long-Term Support) version for your operating system
(Windows, macOS, or Linux).
o Run
the installer and follow the on-screen instructions.
o During
installation, npm will be installed automatically, as npm is bundled with
Node.js.
2.
Verify the installation:
After installation, open your terminal or command prompt and check if Node.js
and npm are installed correctly:
o To
check Node.js, type the following command:
Copy code
node -v
This should display the
version number of Node.js.
o To
check npm, type:
Copy code
npm -v
This will display the
version number of npm.
Step 2: Installing Create
React App
Once Node.js and npm are
installed, you can use Create React App to set up a React project. This
tool helps you quickly set up a development environment with all the necessary
dependencies.
1.
Install Create React App globally:
o Open
your terminal or command prompt.
o To
install Create React App globally, run the following command:
lua
Copy code
npm install -g create-react-app
o The
-g flag installs the tool globally on your system, making it available to
create React projects anywhere on your computer.
2.
Verify the installation:
o After
installation, you can check if Create React App was installed successfully by
typing:
lua
Copy code
create-react-app --version
o This
will return the version number of Create React App if the installation was
successful.
Step 3: Creating a React
Project
Now that Create React App
is installed, you can create your first React project.
1.
Create a new React project:
o In
your terminal or command prompt, navigate to the folder where you want to
create your project. You can use the cd (change directory) command to navigate
to the desired location.
o Once
you're in the right folder, run the following command:
sql
Copy code
npx create-react-app my-first-react-app
§ npx
is a package runner tool that comes with npm, and it is used to execute the
Create React App tool without installing it globally.
§ Replace
my-first-react-app with the name you want to give your project.
§ This
command will create a new folder with the specified name and set up a new React
project inside it.
2.
Navigate to your project directory:
o After
the project is created, change into the project directory using the command:
bash
Copy code
cd my-first-react-app
3.
Project Structure: After
creating the project, you will see the following folder structure:
o node_modules/:
Contains all the libraries (dependencies) that the project needs.
o public/:
Contains the static files like index.html.
o src/:
Contains the React components and application code.
o package.json:
Defines the project’s metadata and dependencies.
o package-lock.json:
Manages the exact versions of the dependencies installed.
Step 4: Running the React
Project Locally
Now that the React
project is set up, it’s time to run it and see it in action!
1.
Start the development server:
o In
your project directory (my-first-react-app), run the following command to start
the React development server:
sql
Copy code
npm start
o This
will start the development server and open your React application in your
default web browser. By default, the application will be available at
http://localhost:3000.
2.
Understand the output:
o Once
the server is running, you should see a React welcome screen that says
"Edit src/App.js and save to reload."
o This
confirms that the React environment is set up correctly.
Step 5: Understanding
Your First React App
Now that your app is
running, let's explore the main files and understand their purpose:
1.
src/App.js:
o This
is the main component of your React application. You will write most of your
React components here.
o When
you edit the code in this file, the changes will be reflected live in the
browser without needing to refresh manually.
2.
src/index.js:
o This
file is the entry point for your React application. It renders the App
component into the index.html file.
3.
public/index.html:
o This
is the only HTML file in a React application. It contains a div element with
the id="root". This is where your React components are rendered.
Step 6: Making Changes to
the App
1.
Open src/App.js in your code editor and
modify the content inside the return() statement to customize the app. For
example:
js
Copy code
function App() {
return (
<div>
<h1>Hello, React!</h1>
<p>Welcome to your first React
application!</p>
</div>
);
}
2.
Save the file, and the changes will
automatically appear in your browser.
Conclusion
Congratulations! You have
successfully set up a React development environment using Node.js, npm, and
Create React App. You’ve created your first React application and run it
locally.
Next Steps:
- Learn
about React components and how to structure your app.
- Experiment
with modifying and adding new components to your app.
- Explore
state, props, and events in React for more interactivity.
By the end of this
session, you should feel comfortable setting up a React project, running it
locally, and making simple modifications.
4o mini
You said:
WRITE SOME ASSIGNMENTS
FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with explanation
ChatGPT said:
ChatGPT
Assignment 1: Install
Node.js, npm, and Create React App
Task:
1.
Install Node.js and npm on your system.
2.
Verify the installation of Node.js and
npm.
3.
Install Create React App globally on your
system.
Steps & Solution:
1.
Install Node.js and npm:
o Go
to the official Node.js website.
o Download
the LTS (Long-Term Support) version for your operating system.
o Run
the installer and follow the on-screen instructions to install Node.js.
o During
installation, npm (Node Package Manager) will also be installed automatically.
2.
Verify Installation:
o Open
your terminal (or command prompt) and type:
Copy code
node -v
This will show the
version of Node.js installed on your system.
Example output:
Copy code
v18.16.0
o Similarly,
check npm by typing:
Copy code
npm -v
This will show the
version of npm installed on your system.
Example output:
Copy code
9.5.0
3.
Install Create React App:
o To
install Create React App globally, use the following command in your terminal:
lua
Copy code
npm install -g create-react-app
o After
the installation completes, you can verify that Create React App is installed
by running:
lua
Copy code
create-react-app --version
4.
Example output:
5.
Copy code
6.
5.0.1
Assignment 2: Creating
Your First React Application
Task:
1.
Use Create React App to create a new React
project.
2.
Run the React app locally and verify that
it’s working correctly.
Steps & Solution:
1.
Create a New React Project:
o In
the terminal or command prompt, navigate to the folder where you want to create
your React project.
o Run
the following command to create a new React project named my-first-react-app:
sql
Copy code
npx create-react-app my-first-react-app
o The
npx command runs the Create React App tool without installing it globally.
2.
Navigate to the Project Folder:
o After
the project is created, navigate into the project directory:
bash
Copy code
cd my-first-react-app
3.
Run the React Application:
o To
start the React development server, use the following command:
sql
Copy code
npm start
o This
will start the local development server and open the React app in your browser
at http://localhost:3000.
o You
should see the default React welcome page with the message: "Edit
src/App.js and save to reload."
Assignment 3: Modifying
the Default React App
Task:
1.
Open the src/App.js file and modify the
existing content to display a custom message.
2.
Add an additional <h2> header with a
welcome message.
Steps & Solution:
1.
Open the src/App.js file:
o In
your project directory (my-first-react-app), open the src/App.js file using a
code editor of your choice (e.g., Visual Studio Code, Sublime Text).
2.
Modify the JSX inside App.js:
Replace the default code inside the return() statement with your own content.
For example:
jsx
Copy code
function App() {
return (
<div>
<h1>Hello, React!</h1>
<h2>Welcome to Your First React App</h2>
</div>
);
}
export default App;
o This
will change the text displayed on the page from "Edit src/App.js and save
to reload" to your custom message.
3.
Save the File:
o After
saving the App.js file, your browser should automatically refresh, and the
changes will appear live:
css
Copy code
Hello, React!
Welcome to Your First
React App
Assignment 4: Understanding
Project Structure
Task:
1.
Explain the purpose of the main
directories and files in the React project.
2.
Identify where you will write most of your
application code.
Steps & Solution:
1.
Main Project Structure:
After running create-react-app, your project directory will look like this:
java
Copy code
my-first-react-app/
├── node_modules/
├── public/
├── src/
├── package.json
├── package-lock.json
└── README.md
2.
Explanation of the Directories and
Files:
o node_modules/: This
folder contains all the libraries and dependencies required for your React
application (e.g., React, ReactDOM, etc.). You usually don’t need to interact
with this folder directly.
o public/:
This folder contains the index.html file, which is the main HTML file for the
app. It also contains other static assets like images and icons. You don’t
write JavaScript here; it's only used for static files.
o src/:
This is the most important folder for your React app. All your React components
and JavaScript files should go here. The default src/App.js file is where you
write most of your React code. You will also create new components in this
folder.
o package.json:
This file contains metadata about your project (such as its name, version, and
dependencies). It also contains scripts for running and building the
application.
o package-lock.json:
This file locks the versions of dependencies installed, ensuring the same
version of libraries is used across different machines.
o README.md:
This file contains information about your project, such as instructions for
setup, usage, and more.
3.
Where to Write Your Application Code:
o Most
of your React code (components, logic, etc.) will be written inside the src/
directory.
o The
main file for your app is src/App.js, where you will build your main app
component.
Assignment 5: Exploring
the public/index.html File
Task:
1.
Open the public/index.html file.
2.
Explain the role of the <div
id="root"></div> element.
3.
Modify the content inside the <body>
tag to add your own HTML element.
Steps & Solution:
1.
Open public/index.html:
o In
the project folder (my-first-react-app), open the public/index.html file.
2.
Understanding the <div
id="root"></div>:
o The
<div id="root"></div> element is where your React
components are injected into the HTML page.
o React
uses this div element as a placeholder to render the UI dynamically. When the
React app runs, it takes the App.js component and renders it inside this div
element.
3.
Modify the index.html File:
o Add
your own custom HTML element inside the <body> tag. For example:
html
Copy code
<body>
<div id="root"></div>
<footer>Created with React</footer>
</body>
4.
Save the File and Reload the App:
o Save
the changes in index.html. After saving, you will see the new <footer>
text ("Created with React") below the React app in the browser.
Conclusion:
These assignments guide
you through the setup and basic understanding of React, including installing
Node.js, npm, and Create React App, creating and running your first React
project, and exploring the project structure. Completing these assignments will
give you a solid foundation to start building React applications.
4o mini
You said:
some more
ChatGPT said:
ChatGPT
Assignment 6: Understanding
JSX Syntax
Task:
1.
Write a simple React component using JSX
that displays a personalized greeting message.
2.
Modify the JSX to use a variable for the
user's name and display the name dynamically.
Steps & Solution:
1.
Create a New Component:
o In
the src folder, create a new file called Greeting.js.
o Inside
Greeting.js, write the following code to display a static greeting message:
jsx
Copy code
function Greeting() {
return <h1>Hello, welcome to React!</h1>;
}
export default Greeting;
2.
Use the Greeting Component in App.js:
o Open
the src/App.js file and import the Greeting component:
jsx
Copy code
import React from 'react';
import Greeting from './Greeting';
function App() {
return (
<div>
<Greeting />
</div>
);
}
export default App;
3.
Use a Variable in JSX:
o Modify
Greeting.js to dynamically display the user's name by using a JavaScript
variable inside JSX. For example:
jsx
Copy code
function Greeting() {
const userName = 'John';
return <h1>Hello, {userName}! Welcome
to React!</h1>;
}
export default Greeting;
4.
Save and Run the Application:
o After
saving both Greeting.js and App.js, your browser should display a personalized
greeting: "Hello, John! Welcome to React!"
Assignment 7: Using Props
to Pass Data to Components
Task:
1.
Create a new component called UserProfile
that accepts name and age as props and displays them.
2.
Use this component in App.js and pass name
and age as props.
Steps & Solution:
1.
Create UserProfile.js Component:
o In
the src folder, create a new file called UserProfile.js.
o Inside
UserProfile.js, write the following code:
jsx
Copy code
function UserProfile(props)
{
return (
<div>
<h2>Name: {props.name}</h2>
<p>Age: {props.age}</p>
</div>
);
}
export default UserProfile;
2.
Use UserProfile Component in App.js:
o Open
App.js and import the UserProfile component:
jsx
Copy code
import React from 'react';
import UserProfile from './UserProfile';
function App() {
return (
<div>
<UserProfile name="John Doe"
age={25} />
<UserProfile name="Jane
Smith" age={30} />
</div>
);
}
export default App;
3.
Save and Run the Application:
o After
saving both files, the React app will display two user profiles with different
names and ages.
Assignment 8: State
Management with useState Hook
Task:
1.
Create a counter that increments when a
button is clicked using the useState hook.
2.
Add a button that decreases the counter
when clicked.
Steps & Solution:
1.
Create the Counter Component:
o In
src/App.js, use the useState hook to create a counter:
jsx
Copy code
import React, { useState
} from 'react';
function App() {
const [counter, setCounter] = useState(0); //
Declare the state
// Function to increment the counter
const increment = () => {
setCounter(counter + 1);
};
// Function to decrement the counter
const decrement = () => {
setCounter(counter - 1);
};
return (
<div>
<h1>Counter: {counter}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default App;
2.
Explanation:
o The
useState(0) function initializes the counter state to 0.
o The
increment function adds 1 to the counter, and the decrement function subtracts
1.
o The
button's onClick event calls the respective functions when clicked.
3.
Save and Run the Application:
o After
saving the changes, the React app will display the current counter value with
two buttons to increment and decrement the counter.
Assignment 9: Handling
Events in React
Task:
1.
Create a form with two input fields (one
for name and one for email).
2.
Display the submitted name and email on
the screen after the form is submitted.
Steps & Solution:
1.
Create the Form in App.js:
o Inside
App.js, create a form with two input fields for name and email:
jsx
Copy code
import React, { useState
} from 'react';
function App() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
// Function to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${name}, Email: ${email}`);
};
return (
<div>
<h1>Form Submission</h1>
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input
type="text"
value={name}
onChange={(e) =>
setName(e.target.value)}
/>
<br />
<label>Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
2.
Explanation:
o The
useState hook is used to store the values of the name and email inputs.
o The
handleSubmit function is triggered when the form is submitted.
o Inside
handleSubmit, e.preventDefault() prevents the default form submission behavior,
and an alert is displayed showing the values of name and email.
3.
Save and Run the Application:
o After
saving the changes, the app will display a form with fields for name and email.
When the form is submitted, the entered name and email will be displayed in an
alert.
Assignment 10: Conditional
Rendering in React
Task:
1.
Create a component that displays either a
"Welcome" message if a user is logged in or a "Please log
in" message if the user is not logged in.
2.
Use a button to toggle the user's login
status.
Steps & Solution:
1.
Create the Conditional Rendering
Component:
o In
App.js, use the useState hook to manage the login status:
jsx
Copy code
import React, { useState
} from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
// Track login status
// Toggle login status
const toggleLogin = () => {
setIsLoggedIn(!isLoggedIn);
};
return (
<div>
<h1>{isLoggedIn ? 'Welcome!' :
'Please log in'}</h1>
<button onClick={toggleLogin}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}
export default App;
2.
Explanation:
o The
isLoggedIn state keeps track of whether the user is logged in.
o The
toggleLogin function toggles the isLoggedIn state between true and false.
o The
JSX conditionally renders either "Welcome!" or "Please log
in" based on the value of isLoggedIn.
o The
button's text and functionality also change depending on whether the user is
logged in.
3.
Save and Run the Application:
o After
saving, the app will display either a "Welcome!" or "Please log
in" message. The button will toggle between "Log In" and
"Log Out" when clicked.
Conclusion:
These assignments deepen
your understanding of key React concepts such as JSX syntax, props, state
management, handling events, and conditional rendering. Working through these
tasks will help you get comfortable with creating interactive React applications.
4o mini
You said:
WRITE 100 no of MCQs FROM
ABOVE CONCEPT
ChatGPT said:
ChatGPT
Here are 100
multiple-choice questions (MCQs) based on the concepts of setting up a React
environment, understanding JSX, props, state management, handling events, and
conditional rendering. The questions are designed to test knowledge and
understanding of fundamental React concepts for beginners.
MCQs on Setting Up React
Environment
1.
Which command installs Node.js and
npm on a Windows system?
o A)
install node
o B)
npm install
o C)
brew install node
o D)
Download from the Node.js official website
2.
What does npm stand for?
o A)
Node Project Manager
o B)
Node Programming Module
o C)
Node Package Manager
o D)
New Project Module
3.
Which command is used to check the
installed version of Node.js?
o A)
node -v
o B)
node -version
o C)
npm --version
o D)
npm -v
4.
What command initializes a new React
project using Create React App?
o A)
npm create react-app
o B)
npx create-react-app
o C)
node create-react-app
o D)
react start
5.
What does the npx command do?
o A)
Installs npm packages
o B)
Executes npm packages without installing globally
o C)
Updates npm
o D)
Uninstalls npm packages
6.
Which file is the main entry point
for a React application created using Create React App?
o A)
index.html
o B)
App.js
o C)
index.js
o D)
main.js
7.
Which command runs a React app
locally?
o A)
npm start
o B)
node start
o C)
npm run app
o D)
node run start
8.
Where do you modify the default HTML
structure of a React app?
o A)
App.js
o B)
index.js
o C)
public/index.html
o D)
App.css
9.
What is the purpose of the public
folder in a React app?
o A)
Stores JavaScript files
o B)
Contains the HTML file and static assets
o C)
Manages npm packages
o D)
Contains React components
10.
Which of the following is true about
the src folder in a React project?
o A)
It contains only HTML files
o B)
It contains JavaScript, CSS, and component files
o C)
It stores public assets
o D)
It is not used in React apps
MCQs on JSX Syntax
11.
What does JSX stand for?
o A)
JavaScript XML
o B)
JavaScript Extension
o C)
JSON XML
o D)
JavaScript Syntax
12.
Which of the following is true about
JSX?
o A)
It is optional in React
o B)
It is used to write HTML in JavaScript
o C)
It replaces JavaScript
o D)
It requires a special browser to run
13.
In JSX, how do you add a JavaScript
expression within HTML tags?
o A)
<> </>
o B)
{ }
o C)
[ ]
o D)
{{ }}
14.
Which of the following is NOT allowed
in JSX?
o A)
Functions
o B)
Objects
o C)
Variables
o D)
For loops
15.
How do you render multiple elements
without adding extra nodes in JSX?
o A)
<> </>
o B)
{ }
o C)
<container></container>
o D)
<div></div>
16.
How do you write a single-line
comment in JSX?
o A)
/* comment */
o B)
{/* comment */}
o C)
// comment
o D)
<!-- comment -->
17.
Which of the following syntax is
correct in JSX?
o A)
<h1>Hello World!</h1>
o B)
<h1>Hello World!>
o C)
h1 Hello World! /h1
o D)
<h1>Hello World!</h1 /
18.
How do you render a variable named name
in JSX?
o A)
<h1>{name}</h1>
o B)
<h1>(name)</h1>
o C)
<h1>{{name}}</h1>
o D)
<h1>$name</h1>
19.
What will <h1>{"Hello"
+ "World"}</h1> render in JSX?
o A)
Error
o B)
Hello
o C)
HelloWorld
o D)
Hello World
20.
What is the correct way to render an
image in JSX?
o A)
<img src="url" />
o B)
<image src="url" />
o C)
<img href="url" />
o D)
<image href="url" />
MCQs on Props in React
21.
What are props in React?
o A)
State variables
o B)
Functions
o C)
Properties passed to components
o D)
JavaScript operators
22.
How are props passed to a component?
o A)
As an argument
o B)
Through the state
o C)
As a variable
o D)
Using functions
23.
In functional components, how do you
access props?
o A)
props.variable
o B)
this.props
o C)
component.props
o D)
useProps()
24.
Which keyword is used to pass data to
a component?
o A)
set
o B)
prop
o C)
props
o D)
data
25.
How do you pass a value to a prop
named title in a component?
o A)
<Component title="Hello" />
o B)
<Component {title}="Hello" />
o C)
<Component title="Hello"/>
o D)
<Component title = Hello />
26.
What happens if you pass a prop with
no value?
o A)
Prop is true by default
o B)
Prop is false by default
o C)
Prop is undefined
o D)
Throws an error
27.
Which of the following components
uses props correctly?
o A)
<Component text={props.text} />
o B)
<Component {props.text} />
o C)
<Component text="props.text" />
o D)
<Component text={(props.text)} />
28.
What will be the output if props.name
is undefined in a component?
o A)
Throws error
o B)
Displays undefined
o C)
Blank
o D)
Displays default value
29.
How can you set default values for
props in a component?
o A)
propDefaults
o B)
defaultProps
o C)
setProps
o D)
initProps
30.
What does children prop refer to in
React?
o A)
Data passed to child components
o B)
Child elements inside a component
o C)
Child component itself
o D)
A function
4o
You said:
more
ChatGPT said:
ChatGPT
Certainly! Here are more
MCQs covering additional topics, such as state management, handling events, and
conditional rendering in React.
MCQs on State Management
31.
What is state in React?
o A)
Static data for a component
o B)
Mutable data that affects rendering
o C)
Properties passed to components
o D)
Immutable data
32.
Which hook is commonly used to manage
state in a functional component?
o A)
useState
o B)
useEffect
o C)
useProps
o D)
useContext
33.
What is the correct syntax to
initialize state with useState?
o A)
const state = useState("initial")
o B)
const [state, setState] = useState("initial")
o C)
const [state] = useState("initial")
o D)
const setState = useState("initial")
34.
In React, calling setState does what
to the component?
o A)
Updates props
o B)
Re-renders the component
o C)
Unmounts the component
o D)
Causes an error
35.
What does useState return?
o A)
An object
o B)
An array
o C)
A string
o D)
A boolean
36.
How can you update the state of a
variable count with setCount?
o A)
setCount(count + 1)
o B)
count = count + 1
o C)
setState(count + 1)
o D)
useState(count + 1)
37.
Where should state variables be
declared in a functional component?
o A)
Inside the return statement
o B)
Inside the useEffect hook
o C)
Outside of the component
o D)
At the top of the component function
38.
If you update the state multiple
times in a single function, how many times does React render?
o A)
Once per update
o B)
Twice per update
o C)
Once, after all updates
o D)
React does not re-render on state changes
39.
What happens if a state update is
triggered with the same value as the current state?
o A)
Re-renders the component
o B)
Triggers an error
o C)
No re-render occurs
o D)
Clears the state
40.
Which of the following can useState
accept as an initial value?
o A)
Only strings
o B)
Only numbers
o C)
Any data type
o D)
Only objects
MCQs on Handling Events
in React
41.
How do you bind a button click event
in React?
o A)
onclick={handleClick}
o B)
onClick={handleClick}
o C)
onclick="handleClick"
o D)
onClick="handleClick"
42.
Which of the following is a valid way
to handle events in React?
o A)
<button click="handleClick">Click</button>
o B)
<button onclick={handleClick}>Click</button>
o C)
<button onClick={handleClick}>Click</button>
o D)
<button click={handleClick}>Click</button>
43.
What is the event parameter in an
event handler function?
o A)
A method to trigger events
o B)
An object representing the event
o C)
The component’s state
o D)
Undefined in React
44.
In React, onClick={handleClick()}
will...
o A)
Bind the function correctly
o B)
Cause an error
o C)
Call the function immediately
o D)
Pass the event object to the function
45.
How do you prevent the default action
of an event in React?
o A)
event.preventDefault()
o B)
preventDefault(event)
o C)
event.stopPropagation()
o D)
event.defaultPrevented()
46.
Which event handler is used for
capturing text input value changes in React?
o A)
onText
o B)
onInputChange
o C)
onChange
o D)
onValue
47.
What will onClick={() =>
setCount(count + 1)} do?
o A)
Update the count value directly
o B)
Create an infinite loop
o C)
Increase count by 1 on click
o D)
Throw an error
48.
Which of the following correctly
passes an argument in an event handler?
o A)
onClick={handleClick(argument)}
o B)
onClick={() => handleClick(argument)}
o C)
onClick={handleClick}
o D)
onClick={(argument) => handleClick}
49.
What is the purpose of the e.stopPropagation()
function in event handling?
o A)
Stops all event functions
o B)
Prevents the event from bubbling up
o C)
Stops all functions in React
o D)
Binds the event function to the parent
50.
Which syntax is correct to handle a
form submission in React?
o A)
onSubmit={submitHandler()}
o B)
onSubmit={submitHandler}
o C)
onSubmit="submitHandler()"
o D)
submitHandler={onSubmit}
MCQs on Conditional
Rendering
51.
Which of the following is used for
conditional rendering in JSX?
o A)
if...else
o B)
Ternary operator
o C)
for...loop
o D)
switch
52.
How do you conditionally render
elements in JSX?
o A)
{condition && <Component />}
o B)
{condition ? Component : ""}
o C)
condition ? <Component />
o D)
<Component if={condition}>
53.
Which operator can help with
conditional rendering in JSX?
o A)
&&
o B)
||
o C)
==
o D)
+=
54.
If you want to display a fallback UI
when a condition is false, what should you use?
o A)
condition ? <Component /> : <Fallback />
o B)
{ condition && <Component /> }
o C)
if (condition) <Component /> else <Fallback />
o D)
condition || <Fallback />
55.
In conditional rendering, what does {isLoggedIn
&& <LogoutButton />} do?
o A)
Always shows the LogoutButton
o B)
Shows LogoutButton only if isLoggedIn is true
o C)
Hides LogoutButton always
o D)
Throws an error
56.
How would you show one of two
components based on the condition isMember?
o A)
isMember ? <Member /> : <Guest />
o B)
isMember && <Member />
o C)
<Guest /> ? <Member /> : <Guest />
o D)
isMember || <Guest />
57.
Which is true about {condition
&& <Component />} syntax?
o A)
It displays Component if condition is true
o B)
It displays Component if condition is false
o C)
It is invalid in JSX
o D)
It always displays Component
58.
What will {isAvailable ? <InStock
/> : <OutOfStock />} render if isAvailable is false?
o A)
InStock
o B)
OutOfStock
o C)
Nothing
o D)
Both components
59.
Which of the following cannot be used
to conditionally render elements in JSX?
o A)
if...else
o B)
Ternary operator
o C)
Logical && operator
o D)
Switch statement
60.
What will {isLoading ?
"Loading..." : "Data Loaded"} display if isLoading is true?
o A)
Loading...
o B)
Data Loaded
o C)
True
o D)
Error
More Questions on React
Basics
61.
What is React mainly used for?
o A)
Server-side development
o B)
Backend programming
o C)
Building user interfaces
o D)
Managing databases
62.
What is the extension for JavaScript
XML files in React?
o A)
.js
o B)
.jsx
o C)
.react
o D)
.xml
63.
What is the default port used by a
React app created by Create React App?
o A)
3000
o B)
5000
o C)
8080
o D)
4000
64.
What is the root component in a React
app?
o A)
App.js
o B)
index.html
o C)
public.html
o D)
main.js
65.
Which file manages the React
application rendering process?
o A)
index.js
o B)
app.js
o C)
public.html
o D)
component.js
These additional
questions provide a broader understanding of React, covering essentials like
event handling, conditional rendering, and state management—key topics for any
React developer. Let me know if you need more details on any specific area!
4o
You said:
more
ChatGPT said:
ChatGPT
Sure! Here’s a new set of
additional MCQs covering component lifecycle, hooks, component styling, React
Router basics, and general React best practices.
MCQs on Component
Lifecycle and Hooks
66.
Which hook is used to run side
effects in functional components?
o A)
useEffect
o B)
useState
o C)
useReducer
o D)
useContext
67.
In which phase is the useEffect hook
called in a functional component?
o A)
Only on initial render
o B)
Only on component unmount
o C)
On every render, based on dependencies
o D)
Only on component destruction
68.
How can you run useEffect only once
after the initial render?
o A)
useEffect(callback, [state])
o B)
useEffect(callback)
o C)
useEffect(callback, [])
o D)
useEffect(callback, {})
69.
What is the purpose of the dependency
array in useEffect?
o A)
To prevent infinite loops
o B)
To specify when the effect should run
o C)
To declare state variables
o D)
To pass props
70.
Which method is called only once when
a class component is first added to the DOM?
o A)
componentDidMount
o B)
componentWillUnmount
o C)
componentDidUpdate
o D)
render
71.
In a class component, where is API
data fetching typically done?
o A)
componentDidMount
o B)
render
o C)
componentWillUnmount
o D)
componentDidUpdate
72.
Which lifecycle method is used for
cleanup activities in class components?
o A)
componentDidMount
o B)
componentWillUnmount
o C)
componentDidUpdate
o D)
render
73.
How do you ensure a useEffect hook
only runs when a specific variable changes?
o A)
Pass the variable in the return statement
o B)
Include the variable in the dependency array
o C)
Place the hook in the callback function
o D)
Use useState to track the variable
74.
What will happen if the dependency
array is empty in useEffect?
o A)
Runs on every render
o B)
Only runs once after the first render
o C)
Causes an error
o D)
Never runs
75.
Which of the following is not a
lifecycle method in React class components?
o A)
componentDidUpdate
o B)
componentWillReceiveProps
o C)
componentWillRender
o D)
componentDidMount
MCQs on Styling in React
76.
How can you apply inline styles to a
React component?
o A)
Using a style object
o B)
Using CSS
o C)
By assigning styles directly to JSX elements as a string
o D)
Using importStyles
77.
Which property is required to use
inline styles in React?
o A)
styles
o B)
css
o C)
style
o D)
stylesheet
78.
How do you set the color of a heading
element to red in inline style?
o A)
style={{color: "red"}}
o B)
style={"color": "red"}
o C)
style="color: red"
o D)
styles={{color: "red"}}
79.
How can you add a CSS file to a React
component?
o A)
Import it in the component file with import './style.css'
o B)
Use @import in JSX
o C)
Add it in the public/index.html
o D)
Add it as inline styling
80.
What is styled-components used for in
React?
o A)
Inline styling in JSX
o B)
CSS framework integration
o C)
To write CSS directly in JavaScript
o D)
To manage JavaScript components only
81.
Which method can be used to
conditionally add classes in React?
o A)
classNames
o B)
addClasses
o C)
classSelector
o D)
toggleClass
82.
Which syntax is correct for applying
a CSS module style in React?
o A)
className={styles.className}
o B)
className="styles.className"
o C)
style={styles.className}
o D)
styles="className"
83.
What is the main advantage of using
CSS modules?
o A)
Automatic styling
o B)
Scoped styling to prevent global conflicts
o C)
Enhanced performance
o D)
Lightweight size
84.
When using CSS-in-JS, styles are
scoped to which elements?
o A)
Globally scoped
o B)
Scoped only to the current component
o C)
Scoped to all child components
o D)
Scoped only to the parent component
85.
What is the syntax for conditional
inline styling in React?
o A)
{condition ? style={{ color: 'blue' }} : style={{ color: 'green' }}
o B)
{style={condition ? { color: 'blue' } : { color: 'green' }}}
o C)
style={condition ? { color: 'blue' } : { color: 'green' }}
o D)
{style={{ color: condition ? 'blue' : 'green' }}}
MCQs on React Router
86.
Which package is commonly used for
routing in React applications?
o A)
react-routing
o B)
react-router-dom
o C)
react-route
o D)
react-navigation
87.
What component from react-router-dom
defines a route path?
o A)
Path
o B)
Switch
o C)
Route
o D)
Router
88.
Which component wraps the entire app
for routing in React?
o A)
AppRouter
o B)
Router
o C)
BrowserRouter
o D)
RouteContainer
89.
How do you navigate programmatically
in React Router v6?
o A)
window.location.href
o B)
navigate
o C)
useNavigate
o D)
redirect
90.
What is the primary use of the <Link>
component in React Router?
o A)
To define routes
o B)
To create navigational links without reloading the page
o C)
To load external pages
o D)
To create buttons
91.
Which of the following is used to
define routes in React Router v6?
o A)
Router
o B)
Routes
o C)
Switch
o D)
Path
92.
Which hook gives you access to route
parameters in React Router?
o A)
useLocation
o B)
useParams
o C)
useHistory
o D)
useRoute
93.
What does exact do in the <Route
exact path="/">?
o A)
Matches only the specified path exactly
o B)
Matches all paths
o C)
Renders the default component
o D)
Prevents the route from rendering
94.
What is the purpose of useLocation
hook in React Router?
o A)
To get the current URL location
o B)
To define routes
o C)
To navigate programmatically
o D)
To add route parameters
95.
How can you render a component only
if a certain condition is true in a route?
o A)
Use conditionalRoute
o B)
Use an inline condition with Route
o C)
Use Switch with Route
o D)
Place condition directly in Routes
MCQs on Best Practices in
React
96.
What is the recommended way to pass
data between components?
o A)
Using context API or props
o B)
Using Redux only
o C)
Direct DOM manipulation
o D)
Using event listeners
97.
Why should you avoid using index as
the key in React?
o A)
It does not uniquely identify elements
o B)
It is not allowed in React
o C)
It makes the component slow
o D)
It changes on every render
98.
Which of the following helps to
improve the performance of a React application?
o A)
Using componentDidMount for rendering
o B)
Memoizing components
o C)
Rendering all data at once
o D)
Avoiding hooks
99.
What does "lifting state
up" mean in React?
o A)
Moving state to a higher-level component to share it with children
o B)
Moving state to a lower-level component
o C)
Increasing the number of state variables
o D)
Resetting the state value
100.
Why should you use functional
components over class components in modern React development?
- A) Functional components are faster - B) Functional components are deprecated
- C) Functional components are recommended for hooks - D) Class components use
more memory
This set covers a wide
range of concepts in React to deepen understanding and prepare students for
real-world React usage. Let me know if you’d like additional areas covered!
