React Components
Components are the building blocks of React. A component is a JavaScript function that accepts inputs (called props) and returns JSX describing what should appear on the screen.
Function Components
// Simplest possible component
function Hello() {
return <h1>Hello, World!</h1>;
}
// Arrow function syntax โ identical behaviour
const Hello = () => <h1>Hello, World!</h1>;
// Usage
<Hello />
Component Composition
Components can include other components. This is called composition and is how you build complex UIs from simple pieces.
// Small, focused components
function Avatar({ src, alt }) {
return <img className="avatar" src={src} alt={alt} />;
}
function Badge({ label, color }) {
return <span style={{ background: color }} className="badge">{label}</span>;
}
// Composed into a larger component
function UserCard({ user }) {
return (
<div className="user-card">
<Avatar src={user.avatarUrl} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.role}</p>
<Badge label={user.online ? "Online" : "Offline"}
color={user.online ? "#22c55e" : "#94a3b8"} />
</div>
);
}
// App uses UserCard
function App() {
const user = { name: "Alice", role: "Engineer", online: true, avatarUrl: "/alice.jpg" };
return <UserCard user={user} />;
}
Exporting Components
// Default export โ one per file
export default function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
// Named exports โ multiple per file
export function PrimaryButton(props) { /* ... */ }
export function SecondaryButton(props) { /* ... */ }
// Importing
import Button from "./Button"; // default
import { PrimaryButton } from "./Button"; // named
NoteBy convention, React component files use PascalCase names:
UserCard.jsx, NavBar.jsx, Button.jsx.The children Prop
function Card({ children, className = "" }) {
return (
<div className={"card " + className}>
{children}
</div>
);
}
// Usage โ anything inside the tags becomes children
<Card className="featured">
<h2>My Title</h2>
<p>Some body text here.</p>
</Card>