Course contentsShow
← React
Lesson 1168 of 2,39630. Composition: Inversion of ControlFree lesson

Merging User Props with Library Props

Learn how to merge user-provided props with library props without clobbering event handlers or classes.

Merging User Props with Library Props

You'll learn how to safely combine user-provided props with your library's default props without overwriting critical handlers or classes.

The Core Challenge

When you build a prop getter function, you need to return props that make your library work (event handlers, ARIA attributes, classes). But users also need to add their own props to the same element. The naive approach of spreading both objects causes prop collisions — if both objects have an onClick or className, one silently clobbers the other.

The Safe Merge Pattern

Your prop getter should intelligently merge props:

function getInputProps(userProps = {}) {
  const libraryProps = {
    value: state.value,
    onChange: handleChange,
    className: 'input-base',
    'aria-labelledby': labelId
  };

  // DON'T: { ...libraryProps, ...userProps } 
  // ❌ User props overwrite library props

  return {
    ...userProps,
    ...libraryProps,
    // Special merge for handlers:
    onChange: (e) => {
      libraryProps.onChange(e);
      userProps.onChange?.(e); // Call user's too
    },
    // Special merge for className:
    className: [libraryProps.className, userProps.className]
      .filter(Boolean)
      .join(' ')
  };
}

The key insight: Event handlers need to be called together, not replaced. Classes need to be concatenated, not overwritten.

Think of It Like...

Imagine merging two instruction manuals. Most sections can just pick one version, but safety warnings need both versions combined — you can't skip either.

Key Takeaway: Always merge event handlers by calling both functions and concatenate className strings to respect both library functionality and user customization.