Course contentsShow
← React
Lesson 259 of 2,3968. Props PatternsFree lesson

Common Use Case: Wrapping Native Elements

Spreading props onto native HTML elements to preserve accessibility attributes, data attributes, and handlers.

Common Use Case: Wrapping Native Elements

What you'll learn: How spreading props onto native HTML elements helps you create wrapper components that preserve all the functionality users expect.

When you create a custom component that wraps a native HTML element (like <button>, <input>, or <div>), you want your wrapper to support all the attributes the native element supports—accessibility labels, data attributes, event handlers, etc.

The spread operator makes this easy. Instead of manually passing through every possible prop, you spread the remaining props directly onto the underlying element.

Why This Matters

Imagine you create a <Button> component that wraps <button>. Users might want to add aria-label, onClick, disabled, or custom data-* attributes. If you only pass specific props you thought of, you'll break these use cases.

The Pattern

function Button({ variant, children, ...rest }) {
  return (
    <button className={`btn-${variant}`} {...rest}>
      {children}
    </button>
  );
}

// Now this works:
<Button 
  variant="primary" 
  onClick={handleClick}
  aria-label="Submit form"
  data-testid="submit-btn"
  disabled={isLoading}
>
  Submit
</Button>

By extracting variant (your custom prop) and spreading ...rest, all standard button attributes flow through automatically. The native <button> receives onClick, aria-label, data-testid, and disabled without you explicitly handling each one.

The Benefit

This pattern keeps your wrapper components flexible and accessible. Users can treat your Button like a real button, with full native functionality preserved.

Key Takeaway: Spread remaining props onto native elements in wrapper components to automatically support all standard HTML attributes, accessibility features, and event handlers without manually passing each one.