Course contentsShow
← React Native
Lesson 342 of 1,5554. Flexbox and Native StylingFree lesson

Dynamic Menu Drawer Geometry

Calculate and animate slide-out drawer widths based on screen availability.

In this lesson, you will learn how to mathematically calculate and animate a slide-out drawer’s width so it remains proportional to the user’s screen size across different devices.

The Problem of Static Widths

In early layout work, you might be tempted to set a drawer width to a hardcoded value like 300. However, on a small phone, this might cover the entire screen, while on a large tablet, it might look tiny and disconnected. To provide a professional experience, the drawer needs to be "geometry-aware."

Calculating the Drawer Width

We use the useWindowDimensions hook to pull the device's current width. Instead of a fixed value, we define the drawer width as a percentage of the available horizontal space. By keeping the drawer at, for example, 80% of the screen width, we ensure the UI remains intuitive regardless of the device.

import { useWindowDimensions } from 'react-native';

const Drawer = () => {
  const { width } = useWindowDimensions();
  // Always occupy 80% of the screen, capped at 300 points
  const drawerWidth = Math.min(width * 0.8, 300);

  return (
    <Animated.View style={{ width: drawerWidth }}>
      {/* Drawer Content */}
    </Animated.View>
  );
};

Animating the Geometry

When animating the drawer’s appearance, we apply this calculated width to our Animated value. By using the useNativeDriver: true option, we offload the transformation to the UI thread, ensuring that as the drawer slides in, the geometry calculations remain smooth and frame-perfect.

The goal is to avoid "layout thrashing" where the component tries to recalculate its bounds mid-animation. By establishing the target drawerWidth before the animation begins and animating the translateX property based on that constant value, we maintain performance while providing a responsive feel. If the user rotates their device, the useWindowDimensions hook will trigger a re-render, allowing your drawer to instantly adjust its geometry to the new screen orientation.

Key Takeaway: Use useWindowDimensions to derive drawer widths as a fraction of screen size, ensuring your layout remains proportional and performant across all hardware.