UseFloating

Last updated: 3.0.0 (04/07/2024) | Added: 2.0.0

The useFloating() hook provides a simple interface for generating CSS styles that respect the safe areas of a given device. It is used in the Floating Toolbar and all button components to provide float functionality.

Usage

import { useFloating, Flex, Text } from "@valence-ui/core";

function MyComponent() { 
    const floating = useFloating({
        "left",       // Horizontal position.
        "top",        // Vertical position
        20,           // Offset
    );
    
    const FlexStyle = { 
        position: "fixed",
        zIndex: 200,
        ...floating.style,    // Generated styles applied
    }
    
    return ( 
        <Flex style={FlexStyle}>
            <Text>Hi there!</Text>
        </Flex>
    )
}

The offset can also be customized far more:

import { useFloating } from "@valence-ui/core";

function MyComponent() { 
    const floating = useFloating({
        "center",       
        "top",        
        offset: { 
            horizontal: 20,        // Will accept any CSS-in-JS valid property
            vertical: "30%",
        }
    );
    
    // OR
    
    const floating = useFloating({
        "left",       
        "top",        
        offset: { 
            // Only the left and top styles will be applied in this case
            top: 20,
            bottom: "30%",
            left: "2rem",
            right: 30,
        }
    );
    
    // etc...
}

useFloating is also responsive, allowing you to define behavior for specific breakpoints:

import { useFloating } from "@valence-ui/core";

function MyComponent() { 
    const floating = useFloating({
        { default: "left", mobile: "right" },       
        "top",        
        offset: { default: 20, tablet: 12, mobile: 5 },
    );
}

Types

PositionHorizontal

type PositionHorizontal = "left" | "right" | "center";

PositionVertical

type PositionVertical = "top" | "bottom" | "center";

FloatingOffset

export type FloatingOffset = number | {
  horizontal: CSSProperties["left"];
  vertical: CSSProperties["top"];
} | {
  top: CSSProperties["top"];
  right: CSSProperties["right"];
  bottom: CSSProperties["bottom"];
  left: CSSProperties["left"];
}

Props

Property
Type
Default
Description

positionHorizontal

"left"

The horizontal position of the element.

positionVertical

"top"

The vertical position of the element.

offset

20

How far from the edges this element is positioned.

calculateOffset

boolean

true

Whether to include safe areas (such as the notch and navigation cutouts in new iPhones) when calculating offsets.


Changelog

  • 3.0.0: Added hook.

Last updated

Was this helpful?