Skip to content

useAvoidKeyboard

A React hook that helps fixed-bottom elements smoothly avoid the on-screen keyboard. When the keyboard appears, it moves the element upward using transform with a smooth transition.

Interface

ts
function useAvoidKeyboard(
  options?: UseAvoidKeyboardOptions
): UseAvoidKeyboardResult;

Parameters

  • optionsUseAvoidKeyboardOptions

    Options to configure the keyboard avoidance behavior.

    • 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.transitionTimingFunctionstring

      Transition timing function for the animation. Defaults to ease-out.

    • options.immediateboolean

      If true, gets the current keyboard height immediately on mount. Defaults to true.

Return Value

  • UseAvoidKeyboardResult

    An 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>
  );
}
tsx
// 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.