Pull Props Out in the Function Signature
Destructuring Props
Most components destructure props directly in the parameter list. Less typing, more readable, easier to see what a component takes.
What you'll learn
- Destructure props in the signature
- Rename and default values inline
Instead of accepting a props object and reaching into it, most
React code destructures props right in the function signature.
Same data, much cleaner.
Before and After
// Without destructuring
function Card(props) {
return (
<div>
<h2>{props.title}</h2>
<p>{props.body}</p>
</div>
);
}
// With destructuring (preferred)
function Card({ title, body }) {
return (
<div>
<h2>{title}</h2>
<p>{body}</p>
</div>
);
} The signature also doubles as documentation — anyone reading
function Card({ title, body }) immediately sees what it takes.
Renaming Inline
If a prop name collides with something else, rename it:
function Item({ id: itemId, name }) {
return <li id={itemId}>{name}</li>;
} Pulling Out Some, Spreading the Rest
...rest collects everything you didn’t pick:
function Button({ kind, ...rest }) {
return <button className={`btn btn--${kind}`} {...rest} />;
}
<Button kind="primary" onClick={save} disabled={busy}>Save</Button> onClick and disabled flow through to the underlying <button>.
You’ll see this pattern in every component library.
When NOT to Destructure
Sometimes you really do want to forward the whole props object
without naming each field:
function Forward(props) {
return <ChildComponent {...props} />;
} Fine in those cases. The destructured form is just much more common.
Up Next
Defaults so you don’t have to pass every prop every time.
Default Props →