Chapter 4 of 4
Props in Practice
Spreading props, forwarding the rest, and building a reusable component.
Two patterns show up constantly once you start building shared components.
Spreading props
The spread operator forwards an entire object as props. It is handy when a parent already holds the right shape, and dangerous when you lose track of what is being passed.
const buttonProps = { type: "submit", disabled: false };
<button {...buttonProps}>Save</button>
// is the same as
<button type="submit" disabled={false}>Save</button>Collecting the rest
A wrapper component usually pulls out the props it cares about and forwards everything else to the underlying element. That keeps the wrapper usable anywhere the plain element would be.
function Button({ variant = "primary", children, ...rest }) {
return (
<button className={"btn btn-" + variant} {...rest}>
{children}
</button>
);
}
// aria-label, onClick, type and anything else pass straight through
<Button variant="ghost" onClick={save} aria-label="Save the document">
Save
</Button>Build a reusable price formatter
Complete formatPrice so it returns a string like $12.50. Use toFixed(2) and prefix with a dollar sign.
What you have learned
- Components should do one job and be declared at module level.
- Props flow down from parent to child and are read only.
childrenturns a component into a container other components can fill.- Rest props let a wrapper stay as flexible as the element it wraps.