Back to Tutorials
Building React Components Tutorial
Lesson 1 of 2: Component Basics
Progress50%
Component Basics
React components are the building blocks of React applications. They are reusable pieces of UI that can have their own state and logic. Key concepts: • Function components vs Class components • JSX syntax for describing UI • Props for passing data • Component composition • Reusability and modularity Types of components: • Functional components (modern approach) • Class components (legacy) • Higher-order components (HOCs) • Custom hooks Best practices: • Keep components small and focused • Use descriptive names • Follow single responsibility principle • Make components reusable
Example
// Basic functional component
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Component with props and default values
function UserCard({ user = { name: 'Guest', email: '' } }) {
return (
<div className="user-card">
<h2>{user.name}</h2>
{user.email && <p>{user.email}</p>}
</div>
);
}
// Component composition
function App() {
const user = { name: 'Alice', email: 'alice@example.com' };
return (
<div>
<Greeting name="World" />
<UserCard user={user} />
<UserCard /> {/* Uses default props */}
</div>
);
}Exercise
Create a Button component that: 1. Accepts 'text', 'onClick', and 'variant' props 2. Has different styles for 'primary' and 'secondary' variants 3. Handles click events 4. Uses the component in an App component
Lesson 1 of 2