Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.4 — Default Values, Rest and Spread Props
React · Example 2 of 3

A Button wrapper with rest and spread

Button names only variant, size and children. Everything else lands in rest and is spread onto the real <button>, so onClick, type, aria-label, disabled and title all work without being listed. Click Save to see its handler run.

Default parameter values give a prop a fallback when the parent leaves it out, ...rest collects every prop you didn't name, and spreading {...rest} onto an element forwards them all at once: handy for wrapper components, but it can quietly pass bad attributes or overwrite your own.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Heading component with a level prop that defaults to 2 and renders <h2>, <h3> and so on. (Hint: a variable like const Tag = "h" + level; can be used as <Tag>.)

02

Write a TextInput wrapper that takes a label prop, renders a <label> around the text and an <input>, and forwards every other prop to the input.

Explain it without notes

01

How do you give a prop a default value in a function component, and when is it used?

02

What do ...rest and {...rest} do in a wrapper component?

03

Why does the position of {...rest} among other attributes matter?

04

Describe two ways spreading props can hide bugs, and how to avoid them.

A Button wrapper with rest and spread

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

primary md [ 'onClick' ]
danger md [ 'type', 'aria-label' ]
ghost sm [ 'disabled', 'title' ]
<button class="btn btn-primary btn-md">Save</button><button class="btn btn-danger btn-md" type="submit" aria-label="Delete this note">Delete</button><button class="btn btn-ghost btn-sm" disabled="" title="Nothing to undo">Undo</button>