Props โ Passing Data to Components
Props (short for properties) are how you pass data into a component. Think of props like function arguments โ they let you customize a component for different use cases.
Passing Props
You pass props like HTML attributes:
passing.jsx
// Passing props to components
function App() {
return (
<div>
<Greeting name="Alice" age={28} isAdmin={true} />
<Greeting name="Bob" age={34} />
<Greeting name="Carol" age={22} isAdmin={false} />
</div>
);
}
// Strings use quotes, everything else uses { }
// age={28} not age="28" (that would be a string)
Receiving Props
The component receives all props as a single object. You can destructure them for cleaner code:
receiving.jsx
// Method 1: receive the props object
function Greeting(props) {
return <h1>Hello, {props.name}! Age: {props.age}</h1>;
}
// Method 2: destructure props (preferred - cleaner)
function Greeting({ name, age, isAdmin }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>Age: {age}</p>
{isAdmin && <span className="badge">Admin</span>}
</div>
);
}
Default Props
You can define default values for props that aren't provided:
defaults.jsx
// Default prop values using destructuring defaults
function Button({ label = "Click me", variant = "primary", disabled = false }) {
return (
<button
className={`btn btn-${variant}`}
disabled={disabled}
>
{label}
</button>
);
}
// Usage:
// <Button /> => "Click me", primary, enabled
// <Button label="Save" /> => "Save", primary, enabled
// <Button label="Delete" variant="danger" />
PropTypes
For larger projects, use PropTypes to document what props a component expects and catch mistakes early:
proptypes.jsx
import PropTypes from 'prop-types';
function UserCard({ name, age, email, isVerified }) {
return (
<div className="user-card">
<h2>{name} {isVerified && "?"}</h2>
<p>{email} ยท Age {age}</p>
</div>
);
}
UserCard.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
email: PropTypes.string.isRequired,
isVerified: PropTypes.bool,
};
// If you pass the wrong type, React logs a warning in development.
Props flow one way โ from parent to child. A child cannot change the props it receives. This is called "one-way data flow" and keeps apps predictable.
Props vs State
This is a crucial distinction:
- Props โ data passed in from outside. Read-only. The parent controls them.
- State โ data managed inside the component. Can change over time. Next lesson!