Understanding Class Components & Creating React App (News App) π
In React, components are the building blocks of any application.
There are two types of components:
β Class Components
β Function Components
Earlier, React applications were mainly built using Class Components.
But now, Function Components with Hooks are more popular.
In this tutorial, we will learn:
What is a Class Component?
A Class Component is a JavaScript class that extends React.Component
and must contain a render() method which returns JSX.
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <h1>Hello from Class Component π</h1>;
}
}
export default Welcome;
Function Component Example
Function Components are simple JavaScript functions that return JSX.
function Welcome() {
return <h1>Hello from Function Component π</h1>;
}
export default Welcome;
Difference Between Class & Function Components
| Class Component | Function Component |
|---|---|
| Uses ES6 Classes | Uses simple JavaScript functions |
Uses this keyword |
No need for this |
| Has lifecycle methods | Uses Hooks (useEffect, useState) |
| More complex | Simple and cleaner |
| Used in older React apps | Preferred in modern React |
Step 1: Create a New React App
Letβs create a new React project named News App.
npx create-react-app news-app
Step 2: Navigate to Project Folder
cd news-app
Step 3: Run the Application
npm start
Your React app will start on:
http://localhost:3000
Step 4: Create a Class Component in News App
import React, { Component } from "react";
export class News extends Component {
render() {
return (
<div>
<h2>Welcome to News App π°</h2>
<p>Latest news will appear here...</p>
</div>
);
}
}
export default News;