Topic 6 of 54
Creating Your First Component
Overview
A React Component is simply a JavaScript function that returns some JSX (markup). Components are the building blocks of any React application. By breaking your UI down into independent, reusable pieces (like a Button, a Header, or a ProfileCard), you make your code infinitely easier to maintain, test, and scale.
Syntax
Always start component names with a Capital letter (PascalCase). React treats lowercase tags as standard HTML (like <div>), and capitalized tags as custom React components.
Basic Functional Component
jsx
// 1. Define a function (Must start with a Capital letter!)
function WelcomeMessage() {
// 2. Return some JSX
return (
<div className="welcome-box">
<h1>Hello, Developer!</h1>
<p>Welcome to the world of React.</p>
</div>
);
}
// 3. Use it like an HTML tag anywhere else in your app
function App() {
return (
<main>
<WelcomeMessage />
</main>
);
}Common Pitfalls
- Naming a component with a lowercase letter (e.g., `function myComponent()`). React will silently fail to render it, assuming it's a non-existent HTML tag.
- Forgetting the `return` keyword. If your component returns `undefined`, React will crash.
Interview Tips
- If asked about Class Components vs Functional Components, state that Functional Components (with Hooks) are the modern standard since React 16.8. Class components are legacy.
Real-World Example
A reusable 'Badge' component used across an e-commerce site for 'New', 'Sale', or 'Out of Stock' tags.
example
jsx
function SaleBadge() {
return (
<span style={{
backgroundColor: 'red',
color: 'white',
padding: '4px 8px',
borderRadius: '4px',
fontWeight: 'bold'
}}>
ON SALE!
</span>
);
}
function ProductCard() {
return (
<div className="card">
<SaleBadge />
<img src="shoes.jpg" alt="Sneakers" />
<h3>Nike Air Max</h3>
</div>
);
}