본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

mergeProps

원문 보기 위키 갱신

여러 세트의 React props를 병합하는 유틸리티예요. 이벤트 핸들러, className, style prop을 지능적으로 처리해서 합성 컴포넌트를 만들 때 유용해요.

출처: Base UI mergeProps

본문

여러 세트의 React props를 병합하는 유틸리티예요. 이벤트 핸들러, className, style prop을 지능적으로 처리해요.

mergeProps는 여러 prop 객체(예: 내부 props + 사용자 props)를 요소에 스프레드할 수 있는 단일 props 세트로 결합해줘요. 특별한 경우가 몇 가지 있는 Object.assign(가장 오른쪽이 우선)처럼 동작해서, 흔한 React 패턴이 예상대로 동작해요.

병합이 동작하는 방식

  • 대부분의 키(className, style, 이벤트 핸들러를 제외한 모든 것)에서는 가장 오른쪽 객체의 값이 우선해요:

    mergeProps({ id: 'a', dir: 'ltr' }, { id: 'b' });
    
  • ref는 병합되지 않아요. 가장 오른쪽 ref만 유지돼요:

    mergeProps({ ref: refA }, { ref: refB });
    
  • className 값은 오른쪽에서 왼쪽으로(가장 오른쪽 먼저) 연결돼요:

    mergeProps({ className: 'a' }, { className: 'b' });
    
  • style 객체는 병합되는데, 가장 오른쪽 스타일의 키가 앞선 것을 덮어써요.

  • 이벤트 핸들러는 병합되고 오른쪽에서 왼쪽으로(가장 오른쪽 먼저) 실행돼요:

    mergeProps({ onClick: a }, { onClick: b });
    
    • React 합성 이벤트의 경우, Base UI는 event.preventBaseUIHandler()를 추가해요. 이걸 호출하면 Base UI의 내부 로직이 실행되지 않아요. 이것은 preventDefault()나 stopPropagation()을 호출하지 않아요.
    • 비합성 이벤트(기본값/객체 값을 가진 커스텀 이벤트)에서는 이 메커니즘을 쓸 수 없어서 모든 핸들러가 항상 실행돼요.

Base UI의 기본 동작 막기

데모

CSS Modules

이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.module.css */
.Container {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.ToggleRow {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Toggle {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  margin: 0;
  border: none;
  border-radius: 0;
  background-color: transparent;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { mergeProps } from '@base-ui/react/merge-props';
import { Toggle } from '@base-ui/react/toggle';
import styles from './index.module.css';

export default function ExamplePreventBaseUIHandler() {
  const [locked, setLocked] = React.useState(true);
  const [pressed, setPressed] = React.useState(true);
  const getToggleProps = (props: React.ComponentProps<'button'>) =>
    mergeProps<'button'>(props, {
      onClick(event) {
        if (locked) {
          event.preventBaseUIHandler();
        }
      },
    });

  return (
    <div className={styles.Container}>
      <div className={styles.ToggleRow}>
        <Toggle
          aria-label="Favorite"
          pressed={pressed}
          onPressedChange={setPressed}
          className={styles.Toggle}
          render={(props, state) => (
            <button type="button" {...getToggleProps(props)}>
              {state.pressed ? <HeartFilledIcon /> : <HeartOutlineIcon />}
            </button>
          )}
        />
        <span className={styles.Label}>Favorite {locked ? '(locked)' : '(unlocked)'}</span>
      </div>
      <button type="button" className={styles.Button} onClick={() => setLocked((l) => !l)}>
        {locked ? 'Unlock' : 'Lock'}
      </button>
    </div>
  );
}

function HeartFilledIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="M7.99961 13.8667C7.88761 13.8667 7.77561 13.8315 7.68121 13.7611C7.43321 13.5766 1.59961 9.1963 1.59961 5.8667C1.59961 3.80856 3.27481 2.13336 5.33294 2.13336C6.59054 2.13336 7.49934 2.81176 7.99961 3.3131C8.49988 2.81176 9.40868 2.13336 10.6663 2.13336C12.7244 2.13336 14.3996 3.80803 14.3996 5.8667C14.3996 9.1963 8.56601 13.5766 8.31801 13.7616C8.22361 13.8315 8.11161 13.8667 7.99961 13.8667Z" />
    </svg>
  );
}

function HeartOutlineIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="m7.99961 4.8232-.75505-.75666c-.40333-.40419-1.0559-.86651-1.91162-.86651-1.46903 0-2.66666 1.19764-2.66666 2.66667 0 .5412.24648 1.2356.75339 2.04713.49581.79376 1.17682 1.59861 1.89311 2.33647 1.06989 1.1022 2.1604 1.9962 2.68705 2.4102.52751-.4149 1.61735-1.3085 2.68657-2.4101.7163-.73792 1.3973-1.54278 1.8932-2.33656.5069-.81154.7533-1.50594.7533-2.04714 0-1.46947-1.1975-2.66667-2.6666-2.66667-.85574 0-1.50831.46232-1.91164.86651zm-.01387-1.52394c-.5031-.49988-1.40673-1.1659-2.6528-1.1659-2.05813 0-3.73333 1.6752-3.73333 3.73334 0 3.3296 5.8336 7.7099 6.0816 7.8944a.532.532 0 0 0 .3184.1056c.112 0 .224-.0352.3184-.1051.248-.185 6.08159-4.5653 6.08159-7.8949 0-2.05867-1.6752-3.73334-3.7333-3.73334-1.24617 0-2.14985.66611-2.65293 1.166q-.0069.00686-.0137.01367c.00002-.00003-.00002.00002 0 0-.00459-.0046-.00927-.00914-.01393-.01377"
      />
    </svg>
  );
}

render prop의 함수 형태를 사용할 때는 props가 자동으로 병합되지 않아요. mergeProps를 사용해 Base UI의 props와 자신의 props를 결합하고, preventBaseUIHandler()를 호출해 Base UI의 내부 로직이 실행되지 않게 할 수 있어요.

객체 대신 함수 전달하기

각 인자는 props 객체 또는 그 시점까지 병합된 props를 받는 함수(왼쪽에서 오른쪽으로)일 수 있고, props 객체를 반환해요. 이미 병합된 것을 바탕으로 다음 props를 계산해야 할 때 유용해요.

함수의 반환 값은 그 시점까지 누적된 props를 완전히 대체한다는 점에 유의하세요. 이전 props의 이벤트 핸들러를 연결하려면 수동으로 호출해야 해요:

const merged = mergeProps(
  {
    onClick(event) {
      // Handler from previous props
    },
  },
  (props) => ({
    onClick(event) {
      // Manually call the previous handler
      props.onClick?.(event);
      // Your logic here
    },
  }),
);

API 레퍼런스

makeEventPreventable

Parameters:

Parameter Type Default Description
event BaseUIEvent<React.SyntheticEvent> - -

Return Value:

type ReturnValue = BaseUIEvent<React.SyntheticEvent>;

mergeClassNames

Parameters:

Parameter Type Default Description
ourClassName string | undefined - -
theirClassName string | undefined - -

Return Value:

type ReturnValue = string | undefined;

mergeProps

여러 세트의 React props를 병합해요. 가장 오른쪽 객체의 필드가 다른 객체의 충돌 필드를 덮어쓰는 Object.assign 패턴을 따라요. 이벤트 핸들러, className, style prop에는 적용되지 않아요.

이벤트 핸들러는 병합되어 오른쪽에서 왼쪽 순서로 호출돼요(가장 오른쪽 핸들러가 먼저, 가장 왼쪽이 마지막 실행). React 합성 이벤트의 경우 가장 오른쪽 핸들러는 event.preventBaseUIHandler()를 호출해 이전(왼쪽에 위치한) 핸들러가 실행되지 않게 할 수 있어요. 비합성 이벤트(기본값/객체 값을 가진 커스텀 이벤트)에서는 모든 핸들러가 막을 능력 없이 항상 실행돼요.

className prop은 클래스를 오른쪽에서 왼쪽 순서로 연결해 병합돼요(가장 오른쪽 클래스가 문자열에서 먼저 나타나요). style prop은 가장 오른쪽 스타일이 앞선 스타일을 덮어쓰며 병합돼요.

Props는 객체로 제공되거나 이전 props를 인자로 받는 함수로 제공될 수 있어요. 함수는 그 시점까지(왼쪽에서 오른쪽으로) 병합된 props를 받아요. 그래서 (obj1, obj2, fn, obj3)의 경우 fn은 obj1과 obj2의 병합된 props를 받아요. 함수는 필요한 경우 이벤트 핸들러를 연결할 책임이 있어요(즉, 우리는 병합 로직을 실행하지 않아요).

함수가 반환한 이벤트 핸들러는 preventBaseUIHandler가 호출되어도 자동으로 막히지 않아요. 핸들러가 직접 event.baseUIHandlerPrevented를 확인하고 true면 중단해야 해요.

Parameters:

Parameter Type Default Description
a InputProps<ElementType> - 병합할 props 객체.
b InputProps<ElementType> - 병합할 props 객체. 이 함수는 a의 충돌 props를 덮어써요.
c? InputProps<ElementType> - 병합할 props 객체. 이 함수는 이전 파라미터들의 충돌 props를 덮어써요.
d? InputProps<ElementType> - 병합할 props 객체. 이 함수는 이전 파라미터들의 충돌 props를 덮어써요.
e? InputProps<ElementType> - 병합할 props 객체. 이 함수는 이전 파라미터들의 충돌 props를 덮어써요.

Return Value:

병합된 props.

type ReturnValue = WithBaseUIEvent<React.ComponentPropsWithRef<ElementType>>;

mergePropsN

mergeProps와 같은 로직으로 임의 개수의 React props를 병합해요. 이 함수는 개별 인자 대신 props 배열을 받아요.

배열 대신 고정된 개수의 인자를 받는 mergeProps보다 성능이 약간 낮아요. 더 나은 성능을 위해 5개 이하의 props 세트를 병합할 때는 mergeProps를 선호하세요.

Parameters:

Parameter Type Default Description
props InputProps<ElementType>[] - 병합할 props 배열.

Return Value:

병합된 props.

type ReturnValue = WithBaseUIEvent<React.ComponentPropsWithRef<ElementType>>;

이 함수는 최대 5개의 인자를 받으며, 각각 props 객체 또는 props 객체를 반환하는 함수예요. 5개보다 많은 props 세트를 병합해야 하면 mergePropsN을 사용하세요.

이 함수는 props 객체 배열 또는 props 객체를 반환하는 함수 배열을 받아요. mergeProps보다 약간 덜 효율적이라 5개보다 많은 props 세트를 병합해야 할 때만 사용하세요.

더 알아보기 (Learn more)