Topic 9 of 54
Destructuring Props
Overview
Writing `props.name`, `props.age`, `props.imageUrl` over and over is tedious and makes code harder to read. Object Destructuring is a standard ES6 feature that allows you to instantly unpack the properties of the props object directly in the function signature. This is the industry standard way to write React components.
Syntax
By wrapping the parameters in `{}` we unpack the object instantly. Notice we can also easily set default values (like `role = "Guest"`) in case the parent forgets to pass it!
Destructuring in the Function Signature
jsx
// ❌ The old/tedious way
function UserCard(props) {
return (
<div>
<h2>{props.firstName} {props.lastName}</h2>
<p>Role: {props.role}</p>
</div>
);
}
// ✅ The modern way (Destructuring)
function UserCard({ firstName, lastName, role = "Guest" }) {
return (
<div>
<h2>{firstName} {lastName}</h2>
<p>Role: {role}</p>
</div>
);
}Common Pitfalls
- Forgetting the curly braces `{}` in the parameter list. If you write `function Card(title)`, `title` will actually be the entire props object, not the string you expected.
Interview Tips
- Destructuring makes it immediately obvious what data a component requires just by looking at line 1. It also allows setting default prop values elegantly.
Real-World Example
Destructuring is especially useful when dealing with many props, like in a complex form input.
example
jsx
// Notice how clean this looks compared to using props.label, props.type, etc.
function FormInput({ label, type = "text", placeholder, isRequired = false, onChange }) {
return (
<div className="input-group">
<label>
{label} {isRequired && <span className="text-red">*</span>}
</label>
<input
type={type}
placeholder={placeholder}
onChange={onChange}
required={isRequired}
/>
</div>
);
}