Understanding Components
Deep dive into React components, props, and how to build reusable UI elements
Understanding React Components
Components are the building blocks of React applications. They let you split the UI into independent, reusable pieces, and think about each piece in isolation.
Types of Components
Function Components
The modern way to write React components using functions:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}Arrow Function Components
A more concise syntax using arrow functions:
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};Props: Passing Data to Components
Props (short for properties) are how you pass data from parent to child components.
function UserCard({ user }) {
return (
<div className="user-card">
<img src={user.avatar} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
// Usage
function App() {
const user = {
name: "John Doe",
email: "john@example.com",
avatar: "/avatar.jpg"
};
return <UserCard user={user} />;
}Component Composition
You can compose components by nesting them:
function Header() {
return (
<header>
<Logo />
<Navigation />
</header>
);
}
function Logo() {
return <img src="/logo.png" alt="Company Logo" />;
}
function Navigation() {
return (
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
);
}Best Practices
- Keep components small and focused: Each component should have a single responsibility
- Use descriptive names: Component names should clearly indicate their purpose
- Extract reusable logic: If you find yourself repeating code, consider creating a new component
- Props validation: Use TypeScript or PropTypes to validate props
Exercise
Try creating a BlogPost component that accepts title, content, and author props and renders them in a structured layout.
In the next lesson, we'll explore how to manage component state using React hooks!