mergeProps 문서
mergeProps는 여러 props 객체를 하나로 합쳐 주는 유틸리티 함수예요. 서로 다른 prop 세트를 가진 컴포넌트를 조합하거나, 기존 컴포넌트의 기능을 확장할 때 특히 유용해요. Bits UI 컴포넌트들도 내부에서 이 함수를 써서 사용자가 넘긴 커스텀 restProps와 Bits UI가 제공하는 prop을 합쳐요.
출처: 문서
본문
개요 (Overview)
mergeProps는 여러 props 객체를 병합하도록 설계된 유틸리티 함수예요. prop 세트가 서로 다른 컴포넌트를 조합하거나 기존 컴포넌트의 기능을 확장할 때 특히 유용하답니다.
Bits UI 컴포넌트는 내부적으로 이 함수를 사용해서, 여러분이 컴포넌트에 넘기는 커스텀 restProps와 Bits UI가 컴포넌트에 제공하는 prop을 병합해요.
주요 특징 (Key Features)
- 여러 props 객체를 병합해요
- 취소를 지원하면서 이벤트 핸들러를 연결해요
- 클래스 이름을 결합해요
- style 객체와 문자열을 병합해요
- 이벤트 핸들러가 아닌 함수들도 연결해요
상세 동작 (Detailed Behavior)
이벤트 핸들러 (Event Handlers)
이벤트 핸들러는 전달된 순서대로 연결돼요. 만약 어떤 핸들러가 event.preventDefault()를 호출하면, 그 뒤에 있는 핸들러들은 실행되지 않아요.
const props1 = { onclick: (e: MouseEvent) => console.log("First click") };
const props2 = { onclick: (e: MouseEvent) => console.log("Second click") };
const mergedProps = mergeProps(props1, props2);
mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click"
preventDefault()가 호출되면:
const props1 = { onclick: (e: MouseEvent) => console.log("First click") };
const props2 = {
onclick: (e: MouseEvent) => {
console.log("Second click");
e.preventDefault();
},
};
const props3 = { onclick: (e: MouseEvent) => console.log("Third click") };
const mergedProps = mergeProps(props1, props2, props3);
mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click" only
props2가 event.preventDefault()를 호출했기 때문에, props3의 onclick 핸들러는 호출되지 않아요.
이벤트 핸들러가 아닌 함수 (Non-Event Handler Functions)
이벤트 핸들러가 아닌 함수도 역시 연결되지만, 뒤에 있는 함수의 실행을 막을 수는 없어요:
const props1 = { doSomething: () => console.log("Action 1") };
const props2 = { doSomething: () => console.log("Action 2") };
const mergedProps = mergeProps(props1, props2);
mergedProps.doSomething(); // Logs: "Action 1" then "Action 2"
클래스 (Classes)
클래스 이름은 clsx를 사용해서 병합해요:
const props1 = { class: "text-lg font-bold" };
const props2 = { class: ["bg-blue-500", "hover:bg-blue-600"] };
const mergedProps = mergeProps(props1, props2);
console.log(mergedProps.class); // "text-lg font-bold bg-blue-500 hover:bg-blue-600"
스타일 (Styles)
style 객체와 문자열은 병합되며, 나중에 있는 속성이 앞의 속성을 덮어써요:
const props1 = { style: { color: "red", fontSize: "16px" } };
const props2 = { style: "background-color: blue; font-weight: bold;" };
const mergedProps = mergeProps(props1, props2);
console.log(mergedProps.style);
// "color: red; font-size: 16px; background-color: blue; font-weight: bold;"
import { mergeProps } from "bits-ui";
const props1 = { style: "--foo: red" };
const props2 = { style: { "--foo": "green", color: "blue" } };
const mergedProps = mergeProps(props1, props2);
console.log(mergedProps.style); // "--foo: green; color: blue;"
더 알아보기 (Learn more)
mergeProps는 컴포넌트를 조합할 때 자주 만나게 되는 유틸리티예요. 특히 커스텀 컴포넌트를 만들 때 prop 타입을 다듬으려면 WithoutChild 같은 타입 헬퍼를 함께 알아두면 좋아요. Portal처럼 하위 컴포넌트를 다른 위치에 렌더링할 때도 이 병합 방식이 그대로 적용되죠.