React Components
Build UI from reusable function components, composition, and children
Overview
React components are JavaScript functions (or classes) that return UI markup. Function components are the modern default. Compose small, focused components rather than monolithic pages.
Syntax / Usage
// Function component
function Button({ label, onClick, variant = 'primary' }) {
return (
<button className={`btn btn-${variant}`} onClick={onClick}>
{label}
</button>
)
}
// Arrow function component
const Card = ({ title, children }) => (
<article className="card">
<h2>{title}</h2>
<div>{children}</div>
</article>
)
// Composition
function Page() {
return (
<Card title="Welcome">
<Button label="Get started" onClick={() => {}} />
</Card>
)
}
export default Page
File naming: PascalCase for components (UserAvatar.tsx), one primary export per file is common.
Examples
Layout with slots via children:
function DashboardLayout({ sidebar, children }) {
return (
<div className="dashboard">
<aside>{sidebar}</aside>
<main>{children}</main>
</div>
)
}
List with keyed items:
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)
}
Common Mistakes
- Defining components inside other components—causes remount every render
- Missing
keyon list items or using array index for reorderable lists - Mixing business logic and presentation—extract hooks or utilities
- Lowercase component names—React treats them as DOM tags
See Also
jsx props use-state conditional-rendering