Components
Creating and composing functional components
What Are Components?
Components are the building blocks of any React application. They let you split the UI into independent, reusable pieces that can be developed and tested in isolation. Think of components like LEGO blocks—small pieces that snap together to build something bigger.
Component Types
React has two types of components: Functional Components (recommended) and Class Components (legacy). Modern React development uses functional components with hooks.
Creating a Functional Component
A functional component is just a JavaScript function that returns JSX:
// Simple functional component
function Greeting() {
return <h1>Hello, World!</h1>;
}
// Arrow function syntax (also common)
const Greeting = () => {
return <h1>Hello, World!</h1>;
};
// Implicit return for simple components
const Greeting = () => <h1>Hello, World!</h1>;
export default Greeting;
Component Naming Rules
- ✓ Component names must start with a capital letter
- ✓ Use PascalCase (e.g., UserProfile, NavBar, ShoppingCart)
- ✓ One component per file is recommended
- ✓ File name should match the component name
// ✓ Correct - starts with capital letter
function UserCard() {
return <div>User Card</div>;
}
// ✗ Wrong - starts with lowercase
function userCard() {
return <div>User Card</div>; // React won't recognize this as a component
}
Composing Components
Components can include other components, allowing you to build complex UIs from simple pieces:
// Small, focused components
function Avatar({ src, alt }) {
return <img src={src} alt={alt} className="avatar" />;
}
function UserName({ name }) {
return <span className="username">{name}</span>;
}
function UserStatus({ isOnline }) {
return (
<span className={isOnline ? 'status-online' : 'status-offline'}>
{isOnline ? '● Online' : '○ Offline'}
</span>
);
}
// Composed component using the smaller ones
function UserCard({ user }) {
return (
<div className="user-card">
<Avatar src={user.avatar} alt={user.name} />
<div>
<UserName name={user.name} />
<UserStatus isOnline={user.isOnline} />
</div>
</div>
);
}
// Using the composed component
function App() {
const user = {
name: 'Alice',
avatar: '/alice.jpg',
isOnline: true
};
return <UserCard user={user} />;
}
Component File Structure
A typical React project organizes components like this:
src/
├── components/
│ ├── Button/
│ │ ├── Button.jsx
│ │ ├── Button.css
│ │ └── index.js
│ ├── Header/
│ │ ├── Header.jsx
│ │ └── index.js
│ └── UserCard/
│ ├── UserCard.jsx
│ └── index.js
├── pages/
│ ├── Home.jsx
│ └── About.jsx
└── App.jsx
Exporting and Importing Components
// Button.jsx - Default export
function Button({ children, onClick }) {
return <button onClick={onClick}>{children}</button>;
}
export default Button;
// Import default export
import Button from './Button';
// -----------------------------------
// utils.jsx - Named exports (multiple components)
export function PrimaryButton({ children }) {
return <button className="btn-primary">{children}</button>;
}
export function SecondaryButton({ children }) {
return <button className="btn-secondary">{children}</button>;
}
// Import named exports
import { PrimaryButton, SecondaryButton } from './utils';
Component Patterns
📦 Container Components
Handle data fetching, state management, and pass data to presentational components
🎨 Presentational Components
Focus purely on how things look, receive data via props
🔄 Higher-Order Components
Functions that take a component and return a new enhanced component
🎣 Custom Hooks
Extract component logic into reusable functions
Real-World Example: Card Component
function Card({ title, description, imageUrl, tags, onAction }) {
return (
<article className="card">
{imageUrl && (
<img
src={imageUrl}
alt={title}
className="card-image"
/>
)}
<div className="card-content">
<h3 className="card-title">{title}</h3>
<p className="card-description">{description}</p>
{tags && tags.length > 0 && (
<div className="card-tags">
{tags.map(tag => (
<span key={tag} className="tag">{tag}</span>
))}
</div>
)}
<button onClick={onAction} className="card-button">
Learn More
</button>
</div>
</article>
);
}
// Usage
function App() {
return (
<Card
title="React Basics"
description="Learn the fundamentals of React"
imageUrl="/react.png"
tags={['React', 'JavaScript', 'Frontend']}
onAction={() => console.log('Clicked!')}
/>
);
}
🎯 Component Best Practices
- ✓ Keep components small and focused on one thing
- ✓ Use meaningful, descriptive names
- ✓ Extract repeated JSX into separate components
- ✓ Put each component in its own file
- ✓ Start with a single component, split when it grows too large
- ✓ Components should be pure—same props should give same output