On this page
Components
Components are independent, reusable pieces of UI. Everything in React is a component.
Function Components (Recommended)
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Arrow function
const Welcome = ({ name }) => <h1>Hello, {name}!</h1>;
// Usage
<Welcome name="Alice" />
Component Composition
Build complex UIs from simple components:
function Avatar({ src, alt }) {
return <img src={src} alt={alt} className="avatar" />;
}
function UserCard({ user }) {
return (
<div className="user-card">
<Avatar src={user.avatar} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
function UserList({ users }) {
return (
<div>
{users.map(user => (
<UserCard key={user.id} user={user} />
))}
</div>
);
}
children Prop
Components can wrap other components:
function Card({ title, children }) {
return (
<div className="card">
<h3>{title}</h3>
<div className="card-body">{children}</div>
</div>
);
}
// Usage
<Card title="Profile">
<p>Name: Alice</p>
<p>Role: Developer</p>
</Card>
Exporting Components
// Button.jsx
export function PrimaryButton({ children, onClick }) {
return <button className="btn-primary" onClick={onClick}>{children}</button>;
}
export function SecondaryButton({ children, onClick }) {
return <button className="btn-secondary" onClick={onClick}>{children}</button>;
}
// App.jsx
import { PrimaryButton, SecondaryButton } from './Button.jsx';
Default Export
// Header.jsx
function Header() {
return <header><h1>My App</h1></header>;
}
export default Header;
// App.jsx
import Header from './Header.jsx';
Component File Convention
One component per file, named after the component:
components/
├── Button.jsx
├── UserCard.jsx
├── Navbar.jsx
└── Footer.jsx
Pure Components
Avoid side effects in render — components should be pure functions of props and state:
// Good — pure
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
// Bad — side effect in render
function BadComponent() {
document.title = 'Changed!'; // Use useEffect instead
return <div>Content</div>;
}
Components are the building blocks of every React application — keep them small, focused, and reusable.