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

Extending components 컴포넌트 확장

원문 보기 위키 갱신

Primer React 컴포넌트의 props가 다루지 못하는 부분을 확장하는 패턴을 다룹니다. 다형적 렌더링을 위한 as prop, 위치 기반 구성을 위한 slot 시스템, 동작 레이어링을 위한 wrapping의 세 가지 메커니즘을 다룹니다.

출처: 문서

본문

Primer React 컴포넌트의 props가 노출하는 범위를 벗어나 확장하는 패턴들입니다. 다형적 렌더링을 위한 as prop, 위치 기반 구성을 위한 slot 시스템, 동작 레이어링을 위한 wrapping을 다룹니다.

Primer 컴포넌트가 필요를 완전히 충족하지 못할 때, 사용할 수 있는 세 가지 메커니즘이 있습니다. 각각은 다른 형태의 문제에 적합합니다.

Pattern Use it when you want to
as prop Change the underlying DOM element or component, but keep all the styling and behavior.
Slot system Inject content into a specific position inside a compound component.
Wrapping Layer behavior, defaults, or context onto a component. Takes extra care if a slot is involved.

이 페이지는 세 패턴 모두와 그들 사이에서 선택하는 방법을 다룹니다.

패턴 1: as prop (Pattern 1: the as prop)

대부분의 Primer 컴포넌트는 다형적(polymorphic)입니다. 기본 요소(예: <Button>의 <button>, <Heading>의 <h1>)를 렌더링하지만, 위에 레이어링된 스타일링과 동작을 잃지 않으면서 기본 요소나 컴포넌트를 바꾸는 as prop을 받아들입니다.

<Button>Submit</Button>                          // renders <button>
<Button as="a" href="/docs">Read docs</Button>   // renders <a href="/docs">
<Button as={NextLink} href="/docs">Read docs</Button>  // renders Next's <Link>

세 가지 렌더링 모두 같은 Button 컴포넌트를 as prop만 달리해 만든 것입니다. 세 가지 모두 Button의 스타일링, 포커스 링, 패딩 등을 상속하지만 기본 DOM 요소는 바뀝니다:

import React from 'react'
import {Button, Stack, Text} from '@primer/react'

export default function AsPropDemo() {
  return (
    <Stack direction="horizontal" gap="normal" align="stretch">
      <Stack.Item grow>
        <Button>Submit form</Button>
      </Stack.Item>
      <Stack.Item grow>
        <Button as="a" href="https://primer.style">Visit Primer</Button>
      </Stack.Item>
      <Stack.Item grow>
        <details>
          <Button as="summary">Toggle details</Button>
          <p style={{margin: 'var(--base-size-8) 0 0'}}>Hidden details revealed by the summary.</p>
        </details>
      </Stack.Item>
    </Stack>
  )
}

내부적으로 어떻게 작동하나 (How it works internally)

다형적 컴포넌트는 src/utils/polymorphic.ts에 있는 Primer의 ForwardRefComponent 타입으로 선언됩니다. 이것은 원래 Radix의 polymorphic helper에서 fork되었습니다.

import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic'

const Button = forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => {
  return <ButtonBase ref={ref} as="button" {...props} />
}) as PolymorphicForwardRefComponent<'button', ButtonProps>

여기서 두 가지가 일어납니다:

  1. TypeScript 타이핑. PolymorphicForwardRefComponent<'button', ButtonProps> 오버로드가 다형적 호출 시그니처를 생성합니다. <Button as="a" href={…} />는 Button이 모든 앵커 props를 받아들이는 것처럼 타입이 지정되며, as="a"일 때 href가 필수가 됩니다.
  2. 런타임 포워딩. 기본 ButtonBase가 as prop을 읽고 그것을 JSX 요소 타입으로 사용합니다. 여러분이 작성한 컴포넌트는 요소 타입을 제어하는 것을 멈추고 그 결정을 소비자에게 포워딩합니다.

언제 사용하나 (When to use it)

  • 시각적 처리를 잃지 않고 Button을 링크로 렌더링(<Button as="a" href="…">).
  • Primer 버튼을 라우터의 Link 컴포넌트에 연결(<Button as={NextLink} to="/page">).
  • 다른 의미론적 수준에서 제목 스타일 사용(<Heading as="h3">).

언제 사용하지 않나 (When not to use it)

  • 복합 컴포넌트 안에서 콘텐츠 위치를 바꾸려 할 때(예: ActionList.Item에 앞 아이콘 추가). 그것은 슬롯이지 다형적 요소가 아닙니다.
  • 많은 호출 지점에 걸쳐 적용되는 기본 prop이나 컨텍스트 조각을 추가하려 할 때. 그것은 래퍼입니다. 계속 읽어 보세요.

Radix의 <Slot asChild>는 밀접하게 관련된 패턴입니다. as="a"로 요소 타입을 지정하는 대신, 소비자가 원하는 자식을 감싸고 부모가 그 위에 props를 병합합니다. 둘 다 다른 이르고노믹스로 같은 문제를 해결합니다. as는 Material UI나 Chakra에서 온 팀에게 더 친숙합니다.

패턴 2: 슬롯 시스템 (Pattern 2: the slot system)

많은 복합 컴포넌트(ActionList, FormControl, Dialog, PageLayout, PageHeader 등)는 추출해 특정 위치에 렌더링하는 이름 있는 "slot" 자식을 받아들입니다. 비교해 보세요:

// Props-based. Explicit, but gets unwieldy as you add more positions.
<ActionList.Item
  leadingVisual={<CheckIcon />}
  description="Status detail"
>
  Approved
</ActionList.Item>

// Slot-based. Reads top-to-bottom; props live with the slot they belong to.
<ActionList.Item>
  <ActionList.LeadingVisual><CheckIcon /></ActionList.LeadingVisual>
  Approved
  <ActionList.Description>Status detail</ActionList.Description>
</ActionList.Item>

slot 기반 형태는 HTML처럼 구성되며 각 슬롯의 props를 슬롯 자체에 붙어 있게 합니다. 이를 작동시키려면 부모가 자식을 검사해 어느 것이 leading visual이고 어느 것이 description이며 어느 것이 본문 텍스트인지 알아내야 합니다. 그것들은 모두 children 안의 요소일 뿐이기 때문입니다.

슬롯 매칭이 어떻게 작동하나 (How slot matching works)

Primer 복합 컴포넌트가 자식을 받으면 그것을 한 번 순회하며 각각을 {slot-name: Component} 구성과 대조합니다. 각 자식에 대해 두 가지 전략을 순서대로 사용합니다:

  1. 직접 컴포넌트 참조. child.type === ActionList.LeadingVisual. 자식이 말 그대로 슬롯 컴포넌트에서 렌더링된 것입니다.
  2. 슬롯 마커 심볼. child.type.__SLOT__ === ActionList.LeadingVisual.__SLOT__. 자식이 모방하는 슬롯에서 마커 심볼을 복사한 다른 컴포넌트에서 렌더링된 것입니다.

두 검사 모두 일치하지 않으면 자식은 rest 버킷으로 떨어져 기본 콘텐츠 위치에 렌더링됩니다.

이를 구동하는 프레임워크는 Primer가 내부적으로 사용하는 useSlots 훅입니다:

const [slots, rest] = useSlots(children, {
  leadingVisual: LeadingVisual,
  trailingVisual: TrailingVisual,
  description: Description,
})
// slots.leadingVisual, slots.trailingVisual, slots.description are the matched children.
// rest is everything else, in original order (the body text in the example above).

부모가 ActionList.Item, FormControl, Dialog, PageLayout, PageHeader 중 무엇이든 같은 매칭이 적용됩니다. 각각 다른 슬롯 이름을 구성합니다.

패턴 3: 래핑 (Pattern 3: wrapping)

세 번째 확장 메커니즘은 가장 흔한 React 패턴입니다. props를 미리 채우거나, 컨텍스트를 레이어링하거나, Primer 조각들을 함께 구성하는 래퍼 컴포넌트를 작성합니다. 대부분의 경우 그냥 작동합니다:

function MyDialog(props) {
  return <Dialog {...props} themedFor="settings" />
}

래핑이 조용히 깨지는 유일한 곳은 slot 컴포넌트를 감쌀 때입니다:

// A thin wrapper around ActionList.LeadingVisual that adds a default color.
function ColoredLeadingVisual({color, children}) {
  return (
    <ActionList.LeadingVisual>
      <span style={{color}}>{children}</span>
    </ActionList.LeadingVisual>
  )
}

<ActionList.Item>
  <ColoredLeadingVisual color="red"><CheckIcon /></ColoredLeadingVisual>
  Approved
</ActionList.Item>

ActionList.Item은 type이 ActionList.LeadingVisual이 아니라 ColoredLeadingVisual인 자식을 보고 심볼 검사로 넘어갑니다. ColoredLeadingVisual은 __SLOT__ 심볼도 없으므로 rest로 들어가 본문 텍스트와 함께 인라인으로 렌더링되고 leading-visual 열이 아닌 곳에 나타납니다.

데모는 실패 모드와 두 가지 수정을 나란히 보여줍니다. 핵심은 __SLOT__이 없는 래퍼가 깨지고, __SLOT__을 복사한 래퍼가 올바르게 동작한다는 것입니다:

/* eslint-disable primer-react/direct-slot-children -- Demonstrates the slot-wrapper
   pattern, including the broken case where a wrapper around ActionList.LeadingVisual
   lacks the __SLOT__ marker. */
import React, {type ReactNode} from 'react'
import {ActionList} from '@primer/react'
import {CheckCircleIcon} from '@primer/octicons-react'

type WrapperProps = {color: string; children: ReactNode}

// Wrapper WITHOUT __SLOT__. ActionList.Item won't recognize it as the
// leading-visual slot, so the icon falls into the body content position.
function BrokenLeadingVisual({color, children}: WrapperProps) {
  return (
    <ActionList.LeadingVisual>
      <span style={{color, display: 'inline-flex'}}>{children}</span>
    </ActionList.LeadingVisual>
  )
}

// Same wrapper, but WITH the __SLOT__ marker copied. ActionList.Item now
// recognizes it as a leading-visual and places it correctly.
function WorkingLeadingVisual({color, children}: WrapperProps) {
  return (
    <ActionList.LeadingVisual>
      <span style={{color, display: 'inline-flex'}}>{children}</span>
    </ActionList.LeadingVisual>
  )
}
;(WorkingLeadingVisual as typeof WorkingLeadingVisual & {__SLOT__?: symbol}).__SLOT__ = (
  ActionList.LeadingVisual as unknown as {__SLOT__: symbol}
).__SLOT__

export default function SlotComparisonDemo() {
  const fg = 'var(--fgColor-success)'
  return (
    <ActionList>
      <ActionList.Item>
        <BrokenLeadingVisual color={fg}><CheckCircleIcon /></BrokenLeadingVisual>
        Wrapper without __SLOT__
      </ActionList.Item>
      <ActionList.Item>
        <WorkingLeadingVisual color={fg}><CheckCircleIcon /></WorkingLeadingVisual>
        Wrapper with __SLOT__ copy
      </ActionList.Item>
      <ActionList.Item>
        <ActionList.LeadingVisual>
          <span style={{color: fg, display: 'inline-flex'}}><CheckCircleIcon /></span>
        </ActionList.LeadingVisual>
        Native ActionList.LeadingVisual
      </ActionList.Item>
    </ActionList>
  )
}

가장 왼쪽 열에서는 아이콘이 본문 텍스트 위에 앉아 있습니다. 그것이 슬롯이 rest로 떨어진 것입니다. 가운데 열의 래퍼는 한 줄짜리 __SLOT__ 복사본을 갖고 있으며 가장 오른쪽(native) <ActionList.LeadingVisual>과 동일하게 렌더링합니다.

슬롯 래퍼를 위한 세 가지 해결책 (Three remediations for slot wrappers)

래퍼가 실제로 무엇을 해야 하는지에 따라 선택합니다.

래퍼가 아무것도 추가하지 않을 때는 재-export (Re-export when the wrapper adds nothing)

"래퍼"가 단지 이름 바꾸기일 뿐이라면(예: ActionList.Description을 자신의 컴포넌트 네임스페이스 아래로 노출), 감싸지 말고 재-export하세요:

import {ActionList} from '@primer/react'

export const MyList = Object.assign(MyListRoot, {
  Item: ActionList.Item,           // identity preserved
  Description: ActionList.Description,
})

<MyList.Description>은 말 그대로 <ActionList.Description>이므로 특별한 처치 없이 직접 참조 검사가 일치합니다. 래퍼가 순전히 API 통합을 위해 존재한다면 거의 항상 올바른 선택입니다.

래퍼가 동작을 추가할 때 __SLOT__ 심볼 복사 (Copy the __SLOT__ symbol when the wrapper adds behavior)

래퍼가 실제로 무언가를 해야 한다면(기본 prop 추가, 컨텍스트 레이어링, 내부 요소 교체), 매커니즘이 여전히 같은 슬롯으로 인식하도록 마커를 복사하세요. 이것이 위 데모에서 가장 왼쪽과 가운데 열을 구분짓는 것입니다.

import {ActionList} from '@primer/react'

function ColoredLeadingVisual({color, children}) {
  return (
    <ActionList.LeadingVisual>
      <span style={{color, display: 'inline-flex'}}>{children}</span>
    </ActionList.LeadingVisual>
  )
}
// Forward the marker so ActionList.Item's slot scan finds ColoredLeadingVisual too.
ColoredLeadingVisual.__SLOT__ = ActionList.LeadingVisual.__SLOT__

__SLOT__을 복사하는 것은 여러분의 컴포넌트가 이 슬롯임을 선언하는 것입니다. 래퍼는 그 위치에서 렌더링될 것에 대한 완전한 소유권을 갖습니다. 원래 슬롯 컴포넌트를 그 안에서 렌더링할 필요는 없습니다. 대부분의 래퍼가 그렇게 하는데, 그것이 슬롯의 내장 스타일, ARIA, 레이아웃을 상속받는 방법이기 때문입니다. 하지만 완전히 다른 것을 렌더링할 이유가 있다면 슬롯 시스템이 막지는 않습니다.

같은 패턴이 어떤 Primer 슬롯에도 작동합니다: FormControl.Label, Dialog.Header, PageLayout.Sidebar, PageHeader.ContextArea. 래퍼가 슬롯이어야 하는 곳이라면 어디든 마커를 복사하세요.

슬롯을 저작할 때는 자신의 useSlots 경계를 소유 (Own your own useSlots boundary when you're authoring slots)

자신만의 슬롯 API를 도입하는 복합 컴포넌트를 만들고 있다면 Primer의 슬롯 스캐너를 확장하려 하지 마세요. 같은 종류의 children 스캔을 직접 실행하고 일치하는 자식을 그들이 속한 곳으로 라우팅하세요.

예를 들어 제목 위에 "eyebrow" 줄을 지원하는 SectionHeader를 원한다고 가정해 봅시다. PageHeader에는 eyebrow 슬롯이 없으므로 자신의 children을 검사하고 eyebrow를 찾아 원하는 위치에 렌더링합니다:

import {Children, isValidElement} from 'react'
import {PageHeader} from '@primer/react'

function Eyebrow({children}) {
  return <span className="eyebrow">{children}</span>
}
Eyebrow.__SLOT__ = Symbol('SectionHeader.Eyebrow')

// Match by direct reference OR by __SLOT__ symbol, so wrappers around
// SectionHeader.Eyebrow are recognised too. Same matcher pattern Primer's
// own useSlots hook uses.
function matchesEyebrow(child) {
  if (!isValidElement(child)) return false
  return child.type === Eyebrow || child.type?.__SLOT__ === Eyebrow.__SLOT__
}

function SectionHeader({title, children}) {
  const childArray = Children.toArray(children)
  const eyebrow = childArray.find(matchesEyebrow)
  return (
    <PageHeader>
      <PageHeader.TitleArea>
        {eyebrow}
        <PageHeader.Title>{title}</PageHeader.Title>
      </PageHeader.TitleArea>
    </PageHeader>
  )
}
SectionHeader.Eyebrow = Eyebrow

완전한 TypeScript 변형:

import React, {Children, isValidElement, type FC, type ReactNode} from 'react'
import {PageHeader, type SlotMarker} from '@primer/react'

type EyebrowProps = {children: ReactNode}
const Eyebrow: FC<EyebrowProps> & SlotMarker = ({children}: EyebrowProps) => (
  <span style={{fontSize: 12, color: 'var(--fgColor-muted)', display: 'block'}}>{children}</span>
)
Eyebrow.__SLOT__ = Symbol('SectionHeader.Eyebrow')

function matchesEyebrow(child: ReactNode): boolean {
  if (!isValidElement(child)) return false
  const childType = child.type as SlotMarker | typeof Eyebrow
  return childType === Eyebrow || (childType as SlotMarker)?.__SLOT__ === Eyebrow.__SLOT__
}

type SectionHeaderProps = {title: string; children?: ReactNode}
function SectionHeaderRoot({title, children}: SectionHeaderProps) {
  const childArray = Children.toArray(children)
  const eyebrow = childArray.find(matchesEyebrow)
  return (
    <PageHeader>
      <PageHeader.TitleArea>
        {eyebrow}
        <PageHeader.Title>{title}</PageHeader.Title>
      </PageHeader.TitleArea>
    </PageHeader>
  )
}

const SectionHeader = Object.assign(SectionHeaderRoot, {Eyebrow})

이것이 useSlots가 내부적으로 하는 일입니다. 공개적으로 배포되면 직접 사용할 수 있고, 그 전까지는 Children.toArray와 참조 검사를 직접 구현하면 됩니다. 여러분의 슬롯은 여러분의 레이어에 있습니다. Primer가 그것을 알 필요는 없습니다.

자신만의 슬롯 컴포넌트 저작 (Authoring slot components of your own)

이름 있는 슬롯이 있는 새 복합 컴포넌트를 만들 때, 소비자가 나중에 그것들을 감쌀 수 있도록 모든 슬롯에 __SLOT__ 심볼을 노출하세요. React.FC와 @primer/react의 SlotMarker 타입을 결합하세요:

import type {FC, ReactNode} from 'react'
import type {SlotMarker} from '@primer/react'

type LabelProps = {children: ReactNode}

const Label: FC<LabelProps> & SlotMarker = ({children}) => (
  <span className="my-label">{children}</span>
)
Label.__SLOT__ = Symbol('MyField.Label')

export const MyField = Object.assign(MyFieldRoot, {Label})

심볼 값은 중요하지 않습니다. 중요한 것은 Label.__SLOT__이 모듈이 평가될 때마다 같은 심볼이라는 것과, 소비자가 리터럴 심볼 값이 아니라 MyField.Label.__SLOT__과 비교한다는 것입니다.

세 패턴 사이에서 선택 (Choosing between the three patterns)

짧은 결정 가이드:

  • 스타일링과 동작의 나머지를 유지하면서 다른 HTML 요소나 컴포넌트를 렌더링하려면 as prop을 사용하세요.
  • 복합 컴포넌트 안의 특정 이름 있는 위치(헤더, leading visual, description)에 콘텐츠를 주입하려면 slot을 사용하세요.
  • 컴포넌트가 사용될 때마다 기본 prop, 컨텍스트, 부작용을 적용하려면 컴포넌트를 wrap하세요. 감싸는 컴포넌트가 슬롯이라면 __SLOT__도 복사하세요.
  • Primer 조각들과 자신의 슬롯 위치를 결합한 새 복합 API를 노출하려면 useSlots 경계를 직접 own하세요.

세 패턴은 서로 구성됩니다. 단일 컴포넌트는 동시에 다형적이고, slot 자식을 받고, 감싸질 수 있습니다.

알아두어야 할 함정 (Gotchas)

슬롯 매칭은 단일 패스이며 첫 매치가 우선 (Slot matching is single-pass, first-match-wins)

두 자식이 같은 슬롯에 모두 일치하면 첫 번째 것만 사용됩니다. 두 번째는 dev-mode 경고("Found duplicate "label" slot. Only the first will be rendered.")를 내고 rest에서 조용히 제거됩니다. 형제로 두 개의 <FormControl.Label> 요소를 렌더링하지 마세요.

각 모듈 인스턴스는 자체 슬롯 심볼을 가진다 (Each module instance has its own slot symbol)

Symbol()은 호출마다 고유합니다. @primer/react의 사본이 두 개 로드되어 있다면(예: 모노레포의 중복 의존성), 그들의 __SLOT__ 값은 같지 않습니다. 이것은 보통 "워크스페이스 의존성을 추가한 후 슬롯이 매칭을 멈췄다"로 나타납니다. npm ls @primer/react가 가장 먼저 확인할 것입니다.

__SLOT__은 런타임 속성이다 (SLOT is a runtime property, not a type-level marker)

Wrapper.__SLOT__ = Original.__SLOT__을 붙이는 것을 잊어도 TypeScript 오류가 발생하지 않습니다. 래퍼는 런타임에 조용히 감지되지 않습니다. 슬롯 래퍼를 배포한다면, 부모 컴포넌트의 슬롯 스캐너가 래퍼를 매칭함을 주장하는 테스트를 작성하세요.

다형적 컴포넌트를 감싸면 다형적 타입이 사라진다 (Wrapping a polymorphic component drops the polymorphic type)

function MyButton(props) { return <Button {...props} /> } 같은 단순한 래퍼는 다형적 호출 시그니처를 버립니다. <MyButton as="a" href="…">는 Button의 기본 props에 대해서만 타입 검사되고 병합된 앵커 props에는 검사되지 않습니다. 래퍼를 통해 다형성을 보존하려면 래퍼 자체를 PolymorphicForwardRefComponent로 선언하세요:

const MyButton = forwardRef<HTMLElement, MyButtonProps>(({as = 'button', ...props}, ref) => {
  return <Button ref={ref} as={as} {...props} />
}) as PolymorphicForwardRefComponent<'button', MyButtonProps>
  • useSlots hook reference. The slot matching algorithm in detail.
  • ActionList component. Slot-based item composition (LeadingVisual, TrailingVisual, Description).
  • FormControl component. Slot-based form fields (Label, Caption, Validation).
  • Dialog component. Header, Body, Footer slots.
  • Button component. Canonical as prop usage.
  • Radix Slot (asChild pattern). Alternative ergonomics for consumer-driven root rendering.
  • Vue named slots. Context on compile-time slot syntax in another framework.

더 알아보기 (Learn more)

  • as prop으로 Button을 링크·라우터 Link·semantic heading으로 렌더링하는 것을 실습해 보세요.
  • useSlots 훅 참조를 읽고 복합 컴포넌트의 slot 매칭 알고리즘을 이해해 보세요.
  • slot 래퍼를 만들 때는 __SLOT__ 마커를 복사하고, 매칭을 주장하는 테스트를 꼭 작성하세요.