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

ref (Ref)

원문 보기 위키 갱신

Bits UI 컴포넌트가 렌더링하는 실제 HTML 요소에 직접 접근하고 싶을 때 쓰는 prop이 ref예요. 필요할 때 DOM을 직접 조작할 수 있게 해주죠. 이 문서에서는 ref의 기본 사용법부터 child 스니펫과 함께 쓸 때 주의할 점, 그리고 직접 ref prop을 만드는 방법까지 다뤄볼게요.

출처: 문서

본문

ref prop은 Bits UI 컴포넌트에서 내부 HTML 요소에 직접 접근할 수 있게 해줘요. 필요할 때 DOM을 직접 조작할 수 있죠.

기본 사용법

HTML 요소를 렌더링하는 모든 Bits UI 컴포넌트는 렌더링된 요소에 접근할 수 있도록 바인딩 가능한 ref prop을 제공해요. 특히 입력에 포커스를 주거나 치수를 측정하는 식으로 요소를 프로그래밍 방식으로 조작할 때 유용합니다.

<script lang="ts">
  import { Accordion } from "bits-ui";
  let triggerRef = $state<HTMLButtonElement | null>(null);
  function focusTrigger() {
    triggerRef?.focus();
  }
</script>
<button onclick={focusTrigger}>Focus trigger</button>
<Accordion.Trigger bind:ref={triggerRef}>Trigger content</Accordion.Trigger>

child 스니펫과 함께

Bits UI는 내부 요소에 대한 참조를 추적하기 위해 요소 ID를 사용해요. 이 방식 덕분에 child 스니펫을 사용할 때도 ref prop이 올바르게 동작합니다.

간단한 위임 예시

ref 바인딩은 위임된 자식 요소/컴포넌트에서도 자동으로 동작해요.

<script lang="ts">
  import CustomButton from "./CustomButton.svelte";
  import { Accordion } from "bits-ui";
  let triggerRef = $state<HTMLButtonElement | null>(null);
  function focusTrigger() {
    triggerRef?.focus();
  }
</script>
<Accordion.Trigger bind:ref={triggerRef}>
  {#snippet child({ props })}
    <CustomButton {...props} />
  {/snippet}
</Accordion.Trigger>

커스텀 ID 사용하기

요소에 커스텀 id를 써야 한다면, ref 바인딩과 올바르게 등록되도록 먼저 부모 컴포넌트에 전달해야 해요:

<script lang="ts">
  import CustomButton from "./CustomButton.svelte";
  import { Accordion } from "bits-ui";
  let triggerRef = $state<HTMLButtonElement | null>(null);
  const myCustomId = "my-custom-id";
</script>
<Accordion.Trigger bind:ref={triggerRef} id={myCustomId}>
  {#snippet child({ props })}
    <!-- The custom ID will be included in props -->
    <CustomButton {...props} />
  {/snippet}
</Accordion.Trigger>

흔한 실수

id를 자식 컴포넌트/요소에 직접 설정하는 것은 피해야 해요. 그러면 ref 바인딩과 요소 사이의 연결이 끊어집니다:

<!-- ❌ This won't work correctly -->
<Accordion.Trigger bind:ref={triggerRef}>
  {#snippet child({ props })}
    <CustomButton {...props} id="my-custom-id" />
  {/snippet}
</Accordion.Trigger>

이 예시에서 Accordion.Trigger 컴포넌트는 커스텀 ID를 알 수 없어서 요소를 추적하지 못해요.

왜 null일 수 있나요?

ref 값은 컴포넌트가 DOM에 마운트되기 전까지는 null일 수 있어요. 이는 getElementById처럼 null을 반환할 수 있는 네이티브 DOM 메서드와도 일관된 동작입니다.

나만의 ref props 만들기

여러분의 커스텀 컴포넌트에서 같은 ref 패턴을 구현하려면, Bits UI가 WithElementRef 타입 헬퍼를 제공해요. 이 헬퍼로 같은 패턴을 따르는 타입 안전한 컴포넌트를 만들 수 있습니다.

<script lang="ts">
  import { WithElementRef } from "bits-ui";
  import type { HTMLButtonAttributes } from "svelte/elements";
  // Define props with the ref type
  let {
    ref = $bindable(null),
    children,
    ...rest
  }: WithElementRef<
    HTMLButtonAttributes & {
      yourPropA: string;
      yourPropB: number;
    },
    HTMLButtonElement
  > = $props();
</script>
<button bind:this={ref} {...rest}>
  {@render children?.()}
</button>

더 알아보기 (Learn more)

ref의 토대가 되는 개념은 child 스니펫의 렌더 위임이에요. 커스텀 요소를 렌더링하며 ref 바인딩까지 유지하는 방식과, 전환 문서에서 실제 요소에 애니메이션을 적용하는 방법을 이어서 보면 좋아요.