How to Create Multiple Class-Based Components in a Single File in React
By Codes With Pankaj
Step 1: Create a New React App (if not already created)
If you don’t have a React app yet, create one with:
Step 2: Plan the Components
We’ll create the following components in a single file:
Header: Displays the title of the app.
Content: Displays the main body text.
Footer: Displays the footer information.
Step 3: Create and Define Multiple Class Components in One File
Open the
src/App.js
file (you can use this file to define multiple components).Replace its content with the following code:
Explanation
Header, Content, and Footer are class-based components defined in a single file (
App.js
).The main
App
component uses these components to assemble the app.Each class component has its own
render()
method that defines its UI.
Step 4: Run the Project
Start the development server:
Open your browser at
http://localhost:3000
.
Output
You’ll see:
Why Use Multiple Class Components in a Single File?
Simpler for Small Projects: Keeps all related components in one place.
Better Organization: Useful when components are tightly related or part of the same module.
Avoid Overhead: Fewer files to manage in small applications.
Best Practices
Use this approach for small projects or related components.
For larger apps, define each component in its own file to keep the code modular and maintainable.
Congratulations! 🎉
You’ve successfully created multiple class-based components in a single file and used them in your React app.
Last updated