Saaj UI

usePositioning

A hook that positions a target element relative to an anchor element.

Installation

npx saaj add usePositioning

Usage

Your target element must be wrapped in a Portal component.
MyComponent.tsx
import React from 'react';
import { View } from 'react-native';
 
import { Portal } from '@/utils/portal';
import { usePositioning } from '@/hooks/usePositioning';
 
export function MyComponent() {
  const anchorRef = React.useRef<View>(null);
  const targetRef = React.useRef<View>(null);
 
  const { x, y } = usePositioning({
    anchorRef,
    targetRef,
    placement: 'bottom',
  });
 
  return (
    <View>
      <View
        ref={anchorRef}
        collapsable={false}
        style={{ width: 120, height: 40, backgroundColor: 'red' }}
      />
      {/* Make sure to wrap the target element in a portal */}
      <Portal>
        <View
          ref={targetRef}
          style={{
            width: 100,
            height: 100,
            backgroundColor: 'blue',
            position: 'absolute',
            left: x,
            top: y,
          }}
        />
      </Portal>
    </View>
  );
}

On this page