0% found this document useful (0 votes)
25 views20 pages

Unit Iii

Uploaded by

Dr. R. Gowri CIT
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)
25 views20 pages

Unit Iii

Uploaded by

Dr. R. Gowri CIT
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/ 20

UNIT III - REACT

Introduction to React – Setting development environment – create app – JSX


syntax – properties and states – components – React routing – API request

1. Setting up Development Environment


 Install Node.js and npm on our machine. Create a new React app
using Create React App.
 Steps:
1. Install Node.js and npm.
2. Open a terminal and run: npx create-react-app my-react-app
3. Navigate into the newly created app directory: cd my-react-app
4. Start the development server: npm start

2. JSX Syntax
 Create a simple React component using JSX.
 Steps:
1. Create a new file MyComponent.js.
2. Define a functional component using JSX in MyComponent.js.
3. Import and render MyComponent in App.js.

Step 1: Create a New Component File


Inside the src folder, create a new file named MyComponent.js.
Step 2: Write the JSX Component
Open MyComponent.js in our code editor and define a simple functional
component using JSX. For example:
// MyComponent.js

import React from 'react';

const MyComponent = () => {


return (
<div>
<h1>Hello, I'm a simple React component!</h1>
<p>This is my JSX content.</p>
</div>
);
};
export default MyComponent;
In this example, we've created a functional component MyComponent that
returns a JSX structure with a heading and a paragraph.
Step 3: Use the Component in App.js
Open src/App.js and import and use our newly created component:
// App.js
import React from 'react';
import MyComponent from './MyComponent'; // Import our component

function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<MyComponent /> {/* Use our component here */}
</div>
);
}

export default App;

Now, save our files.

Step 4: View Our React Component


If the development server is still running, we can see our changes in the browser.
If not, start the server again using:
npm start
Visit http://localhost:3000 in our browser, and we should see our React app with
the simple component rendered.

3. Properties and States


 Create a counter component that uses both props and state.
 Steps:
1. Create a new file Counter.js.
2. Define a class-based component that maintains a count in its state.
3. Pass the count as a prop to another component for display.
4. Implement increment and decrement methods to update the count.

Step 1: Create a new file for the Counter component


Inside the src folder, create a new file named Counter.js.
Step 2: Write the Counter component
Open Counter.js in our code editor and define a class-based component that uses
both props and state:
// Counter.js

import React, { Component } from 'react';

class Counter extends Component {


constructor(props) {
super(props);
this.state = {
count: props.initialCount || 0,
};
}

increment = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};

decrement = () => {
this.setState((prevState) => ({ count: prevState.count - 1 }));
};

render() {
return (
<div>
<h2>Counter Value: {this.state.count}</h2>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div>
);
}
}

export default Counter;

In this example, the Counter component initializes its state with the initial count
value received as a prop. It also has increment and decrement methods to
update the count in the state.
Step 3: Use the Counter component in App.js
Open src/App.js and import and use the Counter component:
// App.js

import React from 'react';


import Counter from './Counter'; // Import our Counter component

function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<Counter initialCount={5} /> {/* Pass an initial count value as a prop */}
</div>
);
}

export default App;

Step 4: View Our React Counter Component


If the development server is still running, we can see our changes in the browser.
If not, start the server again using:
npm start
Visit http://localhost:3000 in our browser, and we should see our React app with
the Counter component rendered. We can click the "Increment" and "Decrement"
buttons to see the count value change.

4. Components
 Build a simple card component and use it in a card list.
 Steps:
1. Create a new file Card.js for a single card component.
2. Create a card list component (CardList.js) that renders multiple
cards.
3. Use the CardList component in App.js.

Step 1: Create a new file for the Card component


Inside the src folder, create a new file named Card.js.
Step 2: Write the Card component
Open Card.js in our code editor and define a functional component for a single
card:
// Card.js

import React from 'react';

const Card = ({ title, content }) => {


return (
<div className="card">
<h3>{title}</h3>
<p>{content}</p>
</div>
);
};

export default Card;

In this example, the Card component takes title and content as props and
displays them within a simple card structure.
Step 3: Create a new file for the CardList component
Inside the src folder, create a new file named CardList.js.
Step 4: Write the CardList component
Open CardList.js in our code editor and define a functional component that
renders multiple Card components:
// CardList.js

import React from 'react';


import Card from './Card';

const CardList = ({ cards }) => {


return (
<div className="card-list">
{cards.map((card, index) => (
<Card key={index} title={card.title} content={card.content} />
))}
</div>
);
};

export default CardList;

In this example, the CardList component takes an array of cards as a prop and
uses the map function to render a Card component for each card in the array.
Step 5: Use the CardList component in App.js
Open src/App.js and import and use the CardList component:
// App.js

import React from 'react';


import CardList from './CardList'; // Import our CardList component
function App() {
const sampleCards = [
{ title: 'Card 1', content: 'Content for Card 1' },
{ title: 'Card 2', content: 'Content for Card 2' },
{ title: 'Card 3', content: 'Content for Card 3' },
];

return (
<div className="App">
<h1>Welcome to My React App</h1>
<CardList cards={sampleCards} /> {/* Pass an array of cards as a prop */}
</div>
);
}

export default App;

Step 6: View Our React Card Components


If the development server is still running, we can see our changes in the browser.
If not, start the server again using:
npm start

Visit http://localhost:3000 in our browser, and we should see our React app with
the CardList component rendered, displaying multiple Card components.

5. React Routing
Implement basic navigation using React Router.

Steps:

1. Install react-router-dom using npm install react-router-dom.
2. Set up routes for different components/pages in App.js.
3. Create components for each route and link them together using
Link.
Step 1: Install react-router-dom
In our project folder, open a terminal and run the following command to install
react-router-dom:
npm install react-router-dom
Step 2: Set Up Routes in App.js
Open src/App.js and set up routes for different components/pages using react-
router-dom. Import necessary components and the BrowserRouter and Route
components:
// App.js

import React from 'react';


import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
return (
<Router>
<div className="App">
<h1>Welcome to My React App</h1>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>

<hr />

{/* Use Routes */}


<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
}

export default App;

The <Routes> component is used to wrap the individual <Route> elements.


Also, the element prop is used to provide the component to be rendered for each
route.
Step 3: Create Home Component
Create a new file named Home.js inside the src folder. Write a simple component
for the Home page:
// Home.js

import React from 'react';

const Home = () => {


return <div>This is the Home page!</div>;
};

export default Home;


Step 4: Create About Component
Create a new file named About.js inside the src folder. Write a simple component
for the About page:
// About.js

import React from 'react';

const About = () => {


return <div>This is the About page!</div>;
};
export default About;
Step 5: View Our React App with Navigation
If the development server is still running, we can see our changes in the browser.
If not, start the server again using:
npm start
Visit http://localhost:3000 in our browser, and we should see our React app with
basic navigation. Clicking on "Home" and "About" should display the respective
components.

6. API Requests
 Fetch data from an external API and display it in our React app.
 Steps:
1. Choose a public API (e.g., JSONPlaceholder, OpenWeatherMap).
2. Create a new component (ApiComponent.js) to fetch and display
data.
3. Use fetch or axios to make API requests within our component.
Step 1: Choose a Public API
In this example, we'll use the JSONPlaceholder API. The base URL is
https://jsonplaceholder.typicode.com. We can choose other public APIs based on
our preference.
Step 2: Create a new component for API Requests
Inside the src folder, create a new file named ApiComponent.js.
Step 3: Write the ApiComponent
Open ApiComponent.js in our code editor and define a class-based component to
fetch and display data from the API:
// ApiComponent.js

import React, { Component } from 'react';

class ApiComponent extends Component {


constructor() {
super();
this.state = {
data: [],
loading: true,
};
}

componentDidMount() {
// Fetch data from the API when the component mounts
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => {
this.setState({
data,
loading: false,
});
})
.catch((error) => {
console.error('Error fetching data:', error);
this.setState({
loading: false,
});
});
}

render() {
const { data, loading } = this.state;

if (loading) {
return <p>Loading data...</p>;
}

return (
<div>
<h2>API Data</h2>
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}
}

export default ApiComponent;

In this example, the ApiComponent class fetches data from the JSONPlaceholder
API (https://jsonplaceholder.typicode.com/posts) in the componentDidMount
lifecycle method. The fetched data is stored in the component's state, and it
renders a list of post titles once the data is loaded.
Step 4: Use the ApiComponent in App.js
Open src/App.js and import and use the ApiComponent:
// App.js

import React from 'react';


import ApiComponent from './ApiComponent'; // Import our ApiComponent

function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<ApiComponent /> {/* Use our ApiComponent here */}
</div>
);
}

export default App;


Step 5: View Our React App with API Data
If the development server is still running, we can see our changes in the browser.
If not, start the server again using:
npm start

Visit http://localhost:3000 in our browser, and we should see our React app
displaying data fetched from the JSONPlaceholder API.

MCQ Questions:
1. What is React primarily used for in web development?
- A) Server-side scripting
- B) Styling web pages
- C) Building user interfaces
- D) Database management

2. Which of the following best describes the key characteristic of React?


- A) Static web pages
- B) Dynamic and interactive user interfaces
- C) Server-side rendering only
- D) Back-end development

3. What tool is commonly used to create a new React app with a predefined
project structure?
- A) Angular CLI
- B) Vue CLI
- C) Create React App
- D) React Native

4. In React development, what is the purpose of the development environment


setup?
- A) Database configuration
- B) Styling decisions
- C) Creating a workspace for coding
- D) Handling server requests
5. In React, what does JSX stand for?
- A) JavaScript XML
- B) JSON Extensible
- C) JSX Syntax
- D) JavaScript Extension

6. In React, what is used to pass data from a parent component to a child


component?
- A) Routes
- B) States
- C) Props
- D) Variables

7. When is it appropriate to use React state in a component?


- A) To handle static data
- B) To manage dynamic data that changes over time
- C) Only in class components
- D) Only for functional components

8. What is the purpose of breaking a UI into reusable components in React?


- A) Reducing code complexity
- B) Enhancing website styling
- C) Improving SEO
- D) Speeding up database queries

9. Which type of React component is typically used for handling lifecycle


methods and state?
- A) Functional component
- B) Stateless component
- C) Class component
- D) Presentational component
10. What is the primary purpose of React Router in a single-page application?
- A) Managing server-side routing
- B) Handling client-side navigation
- C) Controlling database access
- D) Enhancing CSS styling

11. In React Router, what is the purpose of the `<Link>` component?


- A) Creating routes
- B) Handling API requests
- C) Navigating between pages
- D) Styling components

12. When making API requests in a React application, what is the role of the
`fetch` function?
- A) Styling components
- B) Handling form submissions
- C) Retrieving data from an external API
- D) Defining React routes

13. Which term is commonly associated with handling asynchronous API requests
in React?
- A) Callbacks
- B) Promises
- C) Synchronous functions
- D) Static variables

answers for the multiple-choice questions:

1. C) Building user interfaces


2. B) Dynamic and interactive user interfaces

3. C) Create React App


4. C) Creating a workspace for coding
5. A) JavaScript XML
6. C) Props
7. B) To manage dynamic data that changes over time
8. A) Reducing code complexity
9. C) Class component
10. B) Handling client-side navigation
11. C) Navigating between pages
12. C) Retrieving data from an external API
13. B) Promises
**MSQ Question:**

1. Select the features associated with React.


- A) Server-side scripting
- B) Component-based architecture
- C) Dynamic and interactive UI
- D) Cascading Style Sheets (CSS)

2. Choose the tools commonly used for setting up a React development


environment.
- A) React CLI
- B) Create React App
- C) Angular CLI
- D) Vue CLI

3. Identify valid characteristics of JSX syntax in React.


- A) A preprocessor step is required.
- B) It can be directly interpreted by browsers.
- C) It resembles XML/HTML.
- D) It eliminates the need for JavaScript.

4. Select the correct statements about React properties (props) and states.
- A) Props are immutable and passed from parent to child.
- B) States are mutable and used for dynamic data.
- C) Both props and states can be modified directly.
- D) Props are used to manage internal component data.

5. Identify the characteristics associated with React components.


- A) Functional components
- B) Class components
- C) Used for UI composition and reusability
- D) Exclusive to React Native development

6. Choose the statements true about React Routing.


- A) It handles server-side routing.
- B) Allows navigation between different pages in a single-page application.
- C) Requires additional configuration for client-side navigation.
- D) Involves the use of `<Router>` component.

7. Select the accurate statements regarding API requests in React.


- A) Fetching data from an external API can be asynchronous.
- B) `fetch` function is commonly used for making API requests.
- C) API requests are typically handled on the server side in React.
- D) Promises are often used to manage asynchronous API calls.

### Answer Key:


1. B, C
2. B, C
3. B, C
4. A, B
5. A, B, C
6. B, D
7. A, B, D

1. const element = <div>Hello, <strong>React</strong>!</div>;


console.log(element);
What will be printed to the console when this code is executed?
The output will be: <div>Hello, <strong>React</strong>!</div>
=========================================

class Counter extends React.Component {


constructor() {
super();
this.state = { count: 0 };
}

render() {
return <div>Count: {this.state.count}</div>;
}
}

const counterInstance = <Counter />;


console.log(counterInstance.props, counterInstance.state);

What will be printed to the console when this code is executed?


The output will be: {} { count: 0 }

const Greeting = ({ name }) => <p>Hello, {name}!</p>;

const App = () => (


<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);

ReactDOM.render(<App />, document.getElementById('root'));

What will be rendered in the HTML element with the ID 'root' after this
code is executed?

The output will be:


<div>
<p>Hello, Alice!</p>
<p>Hello, Bob!</p>
</div>
const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Us</h2>;

const App = () => (


<div>
<Home />
<About />
</div>
);

ReactDOM.render(<App />, document.getElementById('root'));

What will be rendered in the HTML element with the ID 'root' after this
code is executed?

The output will be:


<div>
<h2>Home Page</h2>
<h2>About Us</h2>
</div>

class ApiComponent extends React.Component {


componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data.title))
.catch(error => console.error('Error fetching data:', error));
}

render() {
return <p>Loading data...</p>;
}
}

ReactDOM.render(<ApiComponent />, document.getElementById('root'));

What will be printed to the console when this code is executed?

The output will be the title of the post fetched from the JSONPlaceholder
API.
Consider the following Angular code snippet:
<!-- app.component.html -->
<div *ngFor="let item of items">
{{ item.name }}
</div>

And in the corresponding component:


// app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
items: any[] = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
];
}

What will be the output on the webpage when this Angular component is
rendered?

You might also like