useRender
커스텀 컴포넌트에서 render prop을 활성화하는 훅을 소개할게요.
본문
useRender 훅은 기본 렌더링 요소를 재정의하는 render prop을 제공하는 커스텀 컴포넌트를 만들 수 있게 해줘요.
예시 (Examples)
커스텀 Text 컴포넌트의 render prop을 사용하면, 소비자가 기본 렌더링되는 p 요소를 다른 태그나 컴포넌트로 바꿔서 쓸 수 있어요.
데모 (Demo)
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Text {
font-size: 0.875rem;
line-height: 1rem;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
strong& {
font-weight: 700;
}
}
/* index.tsx */
'use client';
import { useRender } from '@base-ui/react/use-render';
import { mergeProps } from '@base-ui/react/merge-props';
import styles from './index.module.css';
interface TextProps extends useRender.ComponentProps<'p'> {}
function Text(props: TextProps) {
const { render, ...otherProps } = props;
const element = useRender({
defaultTagName: 'p',
render,
props: mergeProps<'p'>({ className: styles.Text }, otherProps),
});
return element;
}
export default function ExampleText() {
return (
<div>
<Text>Text component rendered as a paragraph tag</Text>
<Text render={<strong />}>Text component rendered as a strong tag</Text>
</div>
);
}
render prop의 콜백 버전은 props가 어떻게 펼쳐지는지 더 세밀하게 제어할 수 있게 해주고, 컴포넌트의 내부 state도 전달해줘요.
데모 (Demo)
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Button {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
gap: 0.25rem;
height: 2rem;
padding: 0 0.75rem;
margin: 0;
outline: 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.25rem;
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;
}
}
}
.count {
display: inline-block;
min-width: 2ch;
text-align: end;
font-variant-numeric: tabular-nums;
}
.suffix {
margin-left: 0.5rem;
padding-left: 0.5rem;
border-left: 1px solid currentColor;
font-size: 0.75rem;
font-weight: 700;
line-height: 1rem;
text-transform: uppercase;
}
/* index.tsx */
'use client';
import * as React from 'react';
import { useRender } from '@base-ui/react/use-render';
import { mergeProps } from '@base-ui/react/merge-props';
import styles from './index.module.css';
interface CounterState {
odd: boolean;
}
interface CounterProps extends useRender.ComponentProps<'button', CounterState> {}
function Counter(props: CounterProps) {
const { render, ...otherProps } = props;
const [count, setCount] = React.useState(0);
const odd = count % 2 === 1;
const state = React.useMemo(() => ({ odd }), [odd]);
const defaultProps: useRender.ElementProps<'button'> = {
className: styles.Button,
type: 'button',
children: (
<React.Fragment>
Counter: <span className={styles.count}>{count}</span>
</React.Fragment>
),
onClick() {
setCount((prev) => prev + 1);
},
'aria-label': `Count is ${count}, click to increase.`,
};
const element = useRender({
defaultTagName: 'button',
render,
state,
props: mergeProps<'button'>(defaultProps, otherProps),
});
return element;
}
export default function ExampleCounter() {
return (
<Counter
render={(props, state) => (
<button {...props}>
{props.children}
<span className={styles.suffix}>{state.odd ? '👎' : '👍'}</span>
</button>
)}
/>
);
}
props 병합 (Merging props)
mergeProps 함수는 두 개 이상의 React props 세트를 병합해요. 다음 세 가지 유형의 props를 안전하게 병합해요:
- 이벤트 핸들러 — 모두 호출되도록
className문자열style속성
mergeProps는 객체를 왼쪽에서 오른쪽으로 병합해서, 인자의 뒤쪽 객체 속성이 앞쪽 것을 덮어써요. props 병합은 커스텀 컴포넌트를 만들 때뿐 아니라, 어떤 Base UI 컴포넌트의 render prop 콜백 버전 안에서도 유용해요.
import { mergeProps } from '@base-ui/react/merge-props';
import styles from './index.module.css';
function Button() {
return (
<Component
render={(props, state) => (
<button
{...mergeProps<'button'>(props, {
className: styles.Button,
})}
/>
)}
/>
);
}
ref 병합 (Merging refs)
커스텀 컴포넌트를 만들 때 내부에서 ref를 제어하면서도 외부 소비자가 자신의 ref를 전달할 수 있게 해야 하는 경우가 많아요. ref 병합을 하면 양쪽 모두 기본 DOM 요소에 접근할 수 있어요. useRender의 ref 옵션이 이를 활성화하며, 병합할 ref들의 배열을 담아요.
React 19에서는 프리미티브 컴포넌트를 만들 때 React.forwardRef()가 필요 없어요. 외부 ref prop이 이미 props 안에 포함되어 있기 때문이에요. 내부 ref는 ref에 전달해서 props.ref와 병합할 수 있어요:
function Text({ render, ...props }: TextProps) {
const internalRef = React.useRef<HTMLElement | null>(null); {/* @highlight-text "internalRef" */}
const element = useRender({
defaultTagName: 'p',
{/* @highlight-start */}
ref: internalRef, {/* @highlight-text "internalRef" */}
{/* @highlight-end */}
props,
render,
});
return element;
}
이전 React 버전에서는 React.forwardRef()를 사용하고, 전달받은 forwarded ref를 자신의 내부 ref와 함께 ref 배열에 추가해야 해요.
위 예시는 React 19를 가정한 것이므로, React 18과 17을 지원하려면 React.forwardRef()를 사용하도록 수정해야 해요.
const Text = React.forwardRef(function Text(
{ render, ...props }: TextProps,
forwardedRef: React.ForwardedRef<HTMLElement>, //@highlight-text "forwardedRef"
) {
const internalRef = React.useRef<HTMLElement | null>(null); // @highlight-text "internalRef"
const element = useRender({
defaultTagName: 'p',
// @highlight-start
// @highlight-text "internalRef" "forwardedRef"
ref: [forwardedRef, internalRef],
// @highlight-end
props,
render,
});
return element;
});
TypeScript
props의 타입을 지정하려면 두 가지 인터페이스가 있어요:
useRender.ComponentProps— 컴포넌트의 외부(공개) props용이에요.renderprop과 HTML 속성의 타입을 지정해요.useRender.ElementProps— 요소의 내부(비공개) props용이에요. HTML 속성만 타입을 지정해요.
// @highlight
interface ButtonProps extends useRender.ComponentProps<'button'> {}
function Button({ render, ...props }: ButtonProps) {
// @highlight
const defaultProps: useRender.ElementProps<'button'> = {
className: styles.Button,
type: 'button',
children: 'Click me',
};
const element = useRender({
defaultTagName: 'button',
render,
props: mergeProps<'button'>(defaultProps, props),
});
return element;
}
Radix UI에서 마이그레이션
Radix UI는 asChild prop을 사용하는 반면, Base UI는 render prop을 사용해요. Base UI에서 합성이 어떻게 동작하는지는 composition 가이드에서 자세히 알아볼 수 있어요.
Radix UI에서는 Slot 컴포넌트로 asChild prop을 구현해요.
import { Slot } from 'radix-ui';
function Button({ asChild, ...props }) {
const Comp = asChild ? Slot.Root : 'button';
return <Comp {...props} />;
}
// Usage
<Button asChild>
<MyButton className="primary">Submit</MyButton>
</Button>;
Base UI에서는 useRender로 render prop을 구현해요. 아래 예시는 위 Radix 예시와 동일한 구현이에요.
import { useRender } from '@base-ui/react/use-render';
function Button({ render, ...props }) {
return useRender({
defaultTagName: 'button',
render,
props,
});
}
// Usage
<Button render={<MyButton className="primary" />}>Submit</Button>;
render prop과 다형성 (polymorphism)
render prop은 주로 이벤트 핸들러와 동작(behavior) prop을 합성하기 위해 설계됐어요. 대부분의 경우 기본 요소와 같은 태그를 렌더링해야 해요.
render를 다형성(다른 태그 렌더링)에 사용하려면 더 주의가 필요해요. 일부 기본 props는 새 요소에 유효하지 않을 수 있으니까요. 예를 들어 type="button"은 <button>에서만 유효해요. 컴포넌트는 렌더링 시점과 하이드레이션 전에 render가 어떤 요소를 만들지 알 수 없으므로, 이런 props에는 명시적인 신호가 필요해요. 그래서 Base UI의 Button이 어떤 기본값을 적용할지 제어하는 nativeButton prop을 제공하는 거예요.
API 레퍼런스
ComponentRenderFn
render prop의 형태예요: 요소에 펼쳐질 props와 컴포넌트 상태를 받아 React 요소를 반환하는 함수예요.
useRender
Base UI 요소를 렌더링해요.
useRender Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
| params | useRender.Parameters<Record<string, unknown>, Element, boolean | undefined> |
- | - |
useRender Return Value:
type ReturnValue = ReactElement | null;
useRender.State
type useRenderState = {};
useRender.ComponentProps
type useRenderComponentProps<
ElementType extends React.ElementType,
TState = {},
RenderFunctionProps = HTMLProps,
> = React.ComponentPropsWithRef<ElementType> & {
render?: ReactElement | ((props: RenderFunctionProps, state: TState) => ReactElement);
};
useRender.ElementProps
type useRenderElementProps =
| (React.PropsWithoutRef<Props> & React.RefAttributes<R | any>)
| Props
| React.ComponentProps<React.ElementType>;
useRender.Parameters
type useRenderParameters<
TState,
RenderedElementType extends Element,
Enabled extends boolean | undefined,
> = {
/** The React element or a function that returns one to override the default element. */
render?: UseRenderRenderProp<TState>;
/** The ref to apply to the rendered element. */
ref?: React.Ref<RenderedElementType>[] | React.Ref<RenderedElementType>;
/**
* The state of the component, passed as the second argument to the `render` callback.
* State properties are automatically converted to data-* attributes.
*/
state?: TState;
/**
* Custom mapping for converting state properties to data-* attributes.
* @example { isActive: (value) => (value ? { 'data-is-active': '' } : null) }
*/
stateAttributesMapping?: StateAttributesMapping<TState>;
/**
* Props to be spread on the rendered element.
* They are merged with the internal props of the component, so that event handlers
* are merged, `className` strings and `style` properties are joined, while other external props overwrite the
* internal ones.
*/
props?: Record<string, unknown>;
/**
* If `false`, the hook will skip most of its internal logic and return `null`.
* This is useful for rendering a component conditionally.
* @default true
*/
enabled?: boolean | undefined;
/**
* The default tag name to use for the rendered element when `render` is not provided.
* @default 'div'
*/
defaultTagName?: keyof React.JSX.IntrinsicElements;
};
useRender.RenderProp
type useRenderRenderProp<TState = Record<string, unknown>> =
ReactElement | ((props: React.HTMLAttributes<any>, state: TState) => ReactElement);
useRender.ReturnValue
type useRenderReturnValue = ReactElement | null;
추가 타입 (Additional Types)
HTMLProps
type HTMLProps<T = any> = React.HTMLAttributes<T> & { ref?: React.Ref<T> };
UseRenderComponentProps
type UseRenderComponentProps<
ElementType extends React.ElementType,
State = {},
RenderFunctionProps = HTMLProps,
> = React.ComponentPropsWithRef<ElementType> & {
render?: ReactElement | ((props: RenderFunctionProps, state: State) => ReactElement);
};
UseRenderElementProps
type UseRenderElementProps =
| (React.PropsWithoutRef<Props> & React.RefAttributes<R | any>)
| Props
| React.ComponentProps<React.ElementType>;
UseRenderParameters
type UseRenderParameters<
State,
RenderedElementType extends Element,
Enabled extends boolean | undefined,
> = {
/** The React element or a function that returns one to override the default element. */
render?: UseRenderRenderProp<State>;
/** The ref to apply to the rendered element. */
ref?: React.Ref<RenderedElementType> | React.Ref<RenderedElementType>[];
/**
* The state of the component, passed as the second argument to the `render` callback.
* State properties are automatically converted to data-* attributes.
*/
state?: State;
/**
* Custom mapping for converting state properties to data-* attributes.
* @example { isActive: (value) => (value ? { 'data-is-active': '' } : null) }
*/
stateAttributesMapping?: StateAttributesMapping<State>;
/**
* Props to be spread on the rendered element.
* They are merged with the internal props of the component, so that event handlers
* are merged, `className` strings and `style` properties are joined, while other external props overwrite the
* internal ones.
*/
props?: Record<string, unknown>;
/**
* If `false`, the hook will skip most of its internal logic and return `null`.
* This is useful for rendering a component conditionally.
* @default true
*/
enabled?: boolean | undefined;
/**
* The default tag name to use for the rendered element when `render` is not provided.
* @default 'div'
*/
defaultTagName?: keyof React.JSX.IntrinsicElements;
};
UseRenderRenderProp
type UseRenderRenderProp<State = Record<string, unknown>> =
ReactElement | ((props: React.HTMLAttributes<any>, state: State) => ReactElement);
UseRenderReturnValue
type UseRenderReturnValue = ReactElement | null;
UseRenderState
type UseRenderState = {};
const element = useRender({
// Input parameters
});