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

Portal (포털)

원문 보기 위키 갱신

Portal을 사용하면 자식 요소를 앱의 다른 부분에 렌더링할 수 있어요. 모달, 오버레이, 팝업처럼 다른 콘텐츠 위에 렌더링해야 하는 컴포넌트에 특히 유용해요. 기본적으로 PortalHost가 HeroUINativeProvider에 포함되어 있어서 별도로 추가할 필요가 없답니다.

출처: 문서

본문

Default Setup

기본적으로 PortalHost는 HeroUINativeProvider에 포함되어 있어서 수동으로 추가할 필요가 없어요. 프로바이더가 포털을 사용하는 모든 컴포넌트에 대해 포털 시스템을 자동으로 설정해요.

Advanced Use Cases

고급 사용 사례에서는 heroui-native에서 직접 Portal과 PortalHost를 import해 커스텀 포털 구현을 만들 수 있어요:

import { Portal, PortalHost } from "heroui-native";
import { View, Text } from "react-native";

function AppLayout() {
  return (
    <View className="flex-1">
      <View className="p-5">
        <Text>Header Content</Text>
      </View>
      
      <View className="flex-1 p-5">
        <Text>Main Content Area</Text>
        <CustomNotification />
      </View>
      
      {/* Portal host positioned at the top of the screen */}
      <PortalHost name="notification-host" />
    </View>
  );
}

function CustomNotification() {
  return (
    <Portal name="notification-portal" hostName="notification-host">
      <View className="absolute top-0 left-0 right-0 bg-blue-500 p-4">
        <Text>This notification appears at the top via Portal</Text>
      </View>
    </Portal>
  );
}

이 예시에서 CustomNotification 컴포넌트는 Portal을 사용해 화면 상단에 위치한 PortalHost의 위치에 콘텐츠를 렌더링해요. 이 덕분에 컴포넌트 트리에서 어디에 정의되었든 관계없이 알림이 다른 모든 콘텐츠 위에 표시돼요.

State Management Considerations

부모 컴포넌트의 상태 변경은 포털 안에 렌더링된 컴포넌트에 예기치 않은 문제를 일으킬 수 있어요. 예를 들어 포털 안에 텍스트 입력이 직접 놓여 있고 부모 컴포넌트가 다시 렌더링되면, 입력의 자동 완성(auto-suggestions)이 초기화되거나 다른 UI 중단이 발생할 수 있어요.

이를 피하려면 포털 콘텐츠를 위한 별도 컴포넌트를 만들어 대화형 컴포넌트(텍스트 입력 같은)의 상태를 포털 안에 유지해요. 이렇게 하면 상태가 부모의 재렌더링으로부터 격리돼요.

Example Pattern

// ❌ Problematic: State in parent causes re-renders that affect portal content
function ParentComponent() {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [inputValue, setInputValue] = useState(""); // State in parent
  
  return (
    <Dialog isOpen={dialogOpen} onOpenChange={setDialogOpen}>
      <Dialog.Trigger>
        <Button>Open Dialog</Button>
      </Dialog.Trigger>
      <Dialog.Portal>
        <Input 
          value={inputValue} 
          onChangeText={setInputValue} 
          // Parent re-renders reset auto-suggestions
        />
      </Dialog.Portal>
    </Dialog>
  );
}

// ✅ Correct: State managed inside separate component within portal
function ParentComponent() {
  const [dialogOpen, setDialogOpen] = useState(false);
  
  return (
    <Dialog isOpen={dialogOpen} onOpenChange={setDialogOpen}>
      <Dialog.Trigger>
        <Button>Open Dialog</Button>
      </Dialog.Trigger>
      <Dialog.Portal>
        <DialogFormContent 
          onClose={() => setDialogOpen(false)} 
          // Form state isolated from parent
        />
      </Dialog.Portal>
    </Dialog>
  );
}

function DialogFormContent({ onClose }: { onClose: () => void }) {
  const [inputValue, setInputValue] = useState(""); // State inside portal
  const [error, setError] = useState("");
  
  return (
    <Dialog.Content>
      <Input 
        value={inputValue} 
        onChangeText={setInputValue}
        // Auto-suggestions preserved during parent re-renders
      />
      <FieldError>{error}</FieldError>
      <Button onPress={onClose}>Close</Button>
    </Dialog.Content>
  );
}

올바른 패턴에서 DialogFormContent 컴포넌트는 부모 컴포넌트와 독립적으로 자체 상태를 관리해요. 이를 통해 부모 재렌더링(예: dialogOpen이 변경될 때)이 입력의 내부 상태에 영향을 주지 않아 자동 완성과 다른 입력 동작이 보존돼요.

API Reference

PortalHost

기본적으로 모든 Portal 컴포넌트의 자식은 PortalHost의 자식으로 렌더링돼요.

Prop Type Note
name string 커스텀 호스트로 사용될 때 제공 (선택 사항)

Portal

Prop Type Note
name* string 고유한 값이어야 해요. 그렇지 않으면 같은 이름의 포털이 원래 포털을 대체해요
hostName string 자식이 커스텀 호스트에 렌더링되어야 할 때 제공 (선택 사항)
children React.ReactNode 포털에 렌더링할 콘텐츠

* Required prop

더 알아보기 (Learn more)