Master React components and props to build reusable UI elements. Learn prop types, default values, and component composition patterns.
Props (short for "properties") are the mechanism React uses to pass data from parent components to child components. Think of props like arguments to a function - they allow components to be dynamic and reusable.
Just as you can call a function with different arguments to get different results, you can use the same component with different props to render different content. This makes your React applications modular, maintainable, and incredibly flexible.
In this lesson, you'll learn how to effectively use props to create reusable components that can adapt to different data and scenarios. You'll also discover advanced prop patterns used in professional React applications.
Props enable one-way data flow from parent to child components. This predictable data flow is one of React's core principles.
Basic Props Example:
1// Parent Component
2function App() {
3 return (
4 <div>
5 <UserCard
6 name="Alice Johnson"
7 age={28}
8 email="[email protected]"
9 isOnline={true}
10 />
11 </div>
12 );
13}
14
15// Child Component
16function UserCard(props) {
17 return (
18 <div className="user-card">
19 <h2>{props.name}</h2>
20 <p>Age: {props.age}</p>
21 <p>Email: {props.email}</p>
22 <span className={props.isOnline ? 'online' : 'offline'}>
23 {props.isOnline ? '🟢 Online' : '🔴 Offline'}
24 </span>
25 </div>
26 );
27}Props Destructuring (Cleaner Syntax):
1// Instead of using props.name, props.age, etc.
2function UserCard({ name, age, email, isOnline }) {
3 return (
4 <div className="user-card">
5 <h2>{name}</h2>
6 <p>Age: {age}</p>
7 <p>Email: {email}</p>
8 <span className={isOnline ? 'online' : 'offline'}>
9 {isOnline ? '🟢 Online' : '🔴 Offline'}
10 </span>
11 </div>
12 );
13}Key Props Rules:
Default Props:
1function Button({ text = 'Click me', type = 'primary', disabled = false }) {
2 return (
3 <button
4 className={`btn btn-${type}`}
5 disabled={disabled}
6 >
7 {text}
8 </button>
9 );
10}
11
12// Usage
13<Button /> // Uses defaults: "Click me", "primary", false
14<Button text="Save" type="success" /> // Custom valuesProps with Objects:
1function ProfileCard({ user, settings }) {
2 return (
3 <div className="profile">
4 <img src={user.avatar} alt={user.name} />
5 <h2>{user.name}</h2>
6 <p>{user.bio}</p>
7 {settings.showEmail && <p>{user.email}</p>}
8 </div>
9 );
10}
11
12// Usage
13const userData = {
14 name: 'John Doe',
15 avatar: '/avatar.jpg',
16 bio: 'React developer',
17 email: '[email protected]'
18};
19
20const appSettings = {
21 showEmail: true,
22 theme: 'dark'
23};
24
25<ProfileCard user={userData} settings={appSettings} />Function Props (Callbacks):
1function TodoItem({ todo, onComplete, onDelete }) {
2 return (
3 <div className="todo-item">
4 <span className={todo.completed ? 'completed' : ''}>
5 {todo.text}
6 </span>
7 <button onClick={() => onComplete(todo.id)}>
8 ✓ Complete
9 </button>
10 <button onClick={() => onDelete(todo.id)}>
11 🗑 Delete
12 </button>
13 </div>
14 );
15}Component composition is the practice of building complex components by combining simpler ones.
Container and Presentation Pattern:
1// Presentation Component (UI only)
2function ProductCard({ product, onAddToCart, onViewDetails }) {
3 return (
4 <div className="product-card">
5 <img src={product.image} alt={product.name} />
6 <h3>{product.name}</h3>
7 <p className="price">${product.price}</p>
8 <p className="description">{product.description}</p>
9 <div className="actions">
10 <button onClick={() => onAddToCart(product.id)}>
11 Add to Cart
12 </button>
13 <button onClick={() => onViewDetails(product.id)}>
14 View Details
15 </button>
16 </div>
17 </div>
18 );
19}
20
21// Container Component (Logic)
22function ProductList({ products }) {
23 const handleAddToCart = (productId) => {
24 // Add to cart logic
25 console.log('Adding product to cart:', productId);
26 };
27
28 const handleViewDetails = (productId) => {
29 // Navigation logic
30 console.log('Viewing details for:', productId);
31 };
32
33 return (
34 <div className="product-list">
35 {products.map(product => (
36 <ProductCard
37 key={product.id}
38 product={product}
39 onAddToCart={handleAddToCart}
40 onViewDetails={handleViewDetails}
41 />
42 ))}
43 </div>
44 );
45}Children Props for Flexible Components:
1function Card({ title, children, className = '' }) {
2 return (
3 <div className={`card ${className}`}>
4 {title && <h2 className="card-title">{title}</h2>}
5 <div className="card-content">
6 {children}
7 </div>
8 </div>
9 );
10}
11
12// Usage - Very flexible!
13<Card title="User Profile">
14 <img src="avatar.jpg" alt="User" />
15 <p>Welcome back, John!</p>
16 <button>Edit Profile</button>
17</Card>
18
19<Card title="Statistics" className="stats-card">
20 <div>Views: 1,234</div>
21 <div>Likes: 567</div>
22</Card>Create a product showcase with reusable components that demonstrate props, composition, and interactivity.
1// Product Card Component
2function ProductCard({ product, onAddToCart, onToggleFavorite }) {
3 const { id, name, price, image, description, rating, isFavorite } = product;
4
5 return (
6 <div className="product-card">
7 <div className="image-container">
8 <img src={image} alt={name} />
9 <button
10 className={`favorite-btn ${isFavorite ? 'favorited' : ''}`}
11 onClick={() => onToggleFavorite(id)}
12 >
13 {isFavorite ? '❤️' : '🤍'}
14 </button>
15 </div>
16
17 <div className="product-info">
18 <h3>{name}</h3>
19 <div className="rating">
20 {'⭐'.repeat(rating)} ({rating}/5)
21 </div>
22 <p className="description">{description}</p>
23 <div className="price">${price.toFixed(2)}</div>
24
25 <button
26 className="add-to-cart-btn"
27 onClick={() => onAddToCart(product)}
28 >
29 Add to Cart 🛒
30 </button>
31 </div>
32 </div>
33 );
34}
35
36// Main App Component
37function App() {
38 const products = [
39 {
40 id: 1,
41 name: "Wireless Headphones",
42 price: 99.99,
43 image: "https://via.placeholder.com/200x200?text=Headphones",
44 description: "High-quality wireless headphones with noise cancellation",
45 rating: 5,
46 isFavorite: false
47 },
48 {
49 id: 2,
50 name: "Smart Watch",
51 price: 199.99,
52 image: "https://via.placeholder.com/200x200?text=Watch",
53 description: "Feature-rich smartwatch with health tracking",
54 rating: 4,
55 isFavorite: true
56 },
57 {
58 id: 3,
59 name: "Portable Speaker",
60 price: 79.99,
61 image: "https://via.placeholder.com/200x200?text=Speaker",
62 description: "Compact speaker with amazing sound quality",
63 rating: 4,
64 isFavorite: false
65 }
66 ];
67
68 const handleAddToCart = (product) => {
69 alert(`Added "${product.name}" to cart!`);
70 };
71
72 const handleToggleFavorite = (productId) => {
73 alert(`Toggled favorite for product ${productId}`);
74 };
75
76 return (
77 <div className="app">
78 <header>
79 <h1>🛍️ React Props Store</h1>
80 <p>Demonstrating component reusability with props</p>
81 </header>
82
83 <div className="products-grid">
84 {products.map(product => (
85 <ProductCard
86 key={product.id}
87 product={product}
88 onAddToCart={handleAddToCart}
89 onToggleFavorite={handleToggleFavorite}
90 />
91 ))}
92 </div>
93
94 <footer>
95 <p>Built with React Components & Props! ⚛️</p>
96 </footer>
97 </div>
98 );
99}This example demonstrates several key concepts:
Props Destructuring:
Function Props (Callbacks):
Conditional Rendering:
Array Mapping:
Component Reusability:
You've mastered components and props! Next, you'll learn about React's most powerful feature - state management:
You'll build interactive components that respond to user input and change over time.
Your progress is saved in this browser, on this device only.