Modern front-end frameworks like React promote building apps using custom components β and for good reason. Custom components provide powerful advantages that improve code quality, scalability, and development speed.
β
1. Reusability
You can reuse the same component multiple times across the app with different data (props/inputs), which saves code repetition.
π2. Encapsulation
Custom components encapsulate their own logic, structure, and styling β preventing conflicts with other parts of the app.
π§ 3. Separation of Concerns
Each component handles one specific part of your UI or logic, making it easier to manage and test.
π οΈ4. Maintainability
If you need to make a UI or logic change, you only update the component in one place instead of all over the codebase.
π§Ό5. Cleaner Code Structure
Breaking your UI into small, logical components makes your app easier to read, understand, and debug.
π€6. Custom Component File Naming
In React, if a component starts with a capital letter, it's treated as a custom component.
If it starts with a lowercase letter, React assumes itβs a built-in HTML tag.
Example:->Creating and Using a Custom Button in React
1. Custom Button Component
import React from 'react';
const CustomButton = ({ label, onClick, type = 'button', className = '' }) => {
return (
<button type={type} onClick={onClick} className={`custom-btn ${className}`}>
{label}
</button>
);
};
export default CustomButton;
2. Using the Custom Component in App
import React from 'react';
import CustomButton from './CustomButton';
const App = () => {
const handleClick = () => {
alert('Button Clicked!');
};
return (
<div>
<h1>Welcome to My App</h1>
<CustomButton
label="Submit"
onClick={handleClick}
className="primary"
/>
<CustomButton
label="Cancel"
onClick={() => console.log('Cancelled')}
className="secondary"
/>
</div>
);
};
export default App;
Top comments (0)