Unit Iii
Unit Iii
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.
function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<MyComponent /> {/* Use our component here */}
</div>
);
}
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>
);
}
}
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
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>
);
}
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.
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
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
return (
<div className="App">
<h1>Welcome to My React App</h1>
<CardList cards={sampleCards} /> {/* Pass an array of cards as a prop */}
</div>
);
}
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
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 />
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
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>
);
}
}
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
function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<ApiComponent /> {/* Use our ApiComponent here */}
</div>
);
}
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
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
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
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.
render() {
return <div>Count: {this.state.count}</div>;
}
}
What will be rendered in the HTML element with the ID 'root' after this
code is executed?
What will be rendered in the HTML element with the ID 'root' after this
code is executed?
render() {
return <p>Loading data...</p>;
}
}
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>
@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?