Understanding Components
What are Components?
Components are independent, reusable pieces of UI. They can be as simple as a button or as complex as an entire page.
Function Components
The simplest way to define a component is with a JavaScript function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Component Composition
Components can contain other components:
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
Props: Passing Data
Props (short for properties) let you pass data from parent to child components:
function UserProfile({ username, avatar }) {
return (
<div className="profile">
<img src={avatar} alt={username} />
<h2>{username}</h2>
</div>
);
}
Conditional Rendering
Show different UI based on conditions:
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}
Lists and Keys
Render multiple components with map():
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Best Practices
- Keep components small and focused
- Use descriptive names
- Extract reusable logic
- Always provide keys for list items