Skip to content

useAvoidKeyboard

useAvoidKeyboard is a React hook that helps fixed-bottom elements avoid the on-screen keyboard. It returns a CSS style that can be applied to position: fixed elements to smoothly move them above the keyboard when it appears.

Interface

ts
function useAvoidKeyboard(
  options: UseAvoidKeyboardOptions
): UseAvoidKeyboardResult;

Parameters

  • optionsUseAvoidKeyboardOptions

    Configuration options.

    • options.safeAreaBottomnumber · 0

      Base bottom offset in pixels when the keyboard is hidden. Useful for accounting for the iPhone home indicator area.

    • options.transitionDurationnumber · 200

      Transition duration in milliseconds for smooth animation.

    • options.transitionTimingFunctionCSSProperties['transitionTimingFunction'] · 'ease-out'

      Transition timing function for the animation.

    • options.immediateboolean · true

      If true, gets the initial keyboard height on mount.

Return Value

  • UseAvoidKeyboardResult

    object containing the CSS style for keyboard avoidance.

    • styleCSSProperties

      CSS style object to apply to the fixed bottom element. Contains transform and transition properties.

Example

tsx
function FixedBottomCTA() {
  const { style } = useAvoidKeyboard();

  return (
    <div
      style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        ...style,
      }}
    >
      <button>Submit</button>
    </div>
  );
}

// With safe area bottom offset (e.g., for iPhone home indicator)
function FixedBottomCTA() {
  const { style } = useAvoidKeyboard({ safeAreaBottom: 34 });

  return (
    <div
      style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        ...style,
      }}
    >
      <button>Submit</button>
    </div>
  );
}

Released under the MIT License.