Destructuring Props and Default Prop Values
Destructuring Props and Default Prop Values
1. The Power of Prop Destructuring
In standard JavaScript functions, accessing properties repeatedly through an object parameter (props.title, props.subtitle, props.onClick) creates verbose, repetitive code.
Modern React applications universally leverage ES6 Object Destructuring directly within the component function parameter signature:
Without Destructuring:
With Parameter Destructuring:
Destructuring makes the component's contract immediately obvious at a glance: any developer inspecting the function header can immediately see all the props the component expects.
2. Providing Default Prop Values
When building reusable design system components, certain props should have sensible defaults if the consumer fails to provide them.
You can assign ES6 default parameter values directly inside the destructuring pattern:
Usage:
Note: A default value is applied if the incoming prop is undefined or omitted entirely. If the parent explicitly passes null, the default value is not applied, because null is an intentional value in JavaScript.
3. Rest Props and Prop Spreading
When creating wrapper components (such as a custom <TextInput> or <Card>), you frequently want to extract a few specific props and forward all remaining standard HTML attributes (id, placeholder, aria-*, onFocus) to the underlying element.
You can combine destructuring with the ES6 Rest syntax (...rest) and JSX Spread ({...rest}):
Usage:
Practice Quiz
function Avatar({ size = 50 }), what value will size receive if the parent calls <Avatar size={undefined} />?size receive if the parent calls <Avatar size={null} /> in the previous question?<input {...restProps} /> accomplish?Passing Children and Composing Components
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Component Props and Read-Only Data Flow | Passing Children and Composing Components |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.