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

Responsive Typography Scaling

Create a typography scale that adjusts text sizing based on container width rather than device density.

In this lesson, you will learn how to build a typography system that scales text based on the size of the container, ensuring your text remains proportional regardless of whether it lives in a narrow sidebar or a wide hero section.

Moving Beyond Device Density

Usually, we rely on the device’s pixel density (or system font settings) to determine text size. However, this creates a problem: a title that looks great on a phone’s full width will look cramped inside a smaller modal or a split-screen view. Instead of scaling based on the device, we scale based on the container’s width.

Implementing Container-Aware Scaling

To achieve this, we use the onLayout prop. This allows a component to "measure" itself the moment it renders. By capturing the width of the parent component, we can calculate a dynamic font size.

const ResponsiveText = ({ children }) => {
  const [fontSize, setFontSize] = useState(16);

  const onLayout = (event) => {
    const { width } = event.nativeEvent.layout;
    // Scale text to be roughly 10% of container width
    const newSize = Math.max(12, width * 0.1); 
    setFontSize(newSize);
  };

  return (
    <Text onLayout={onLayout} style={{ fontSize }}>
      {children}
    </Text>
  );
};

Why This Matters

When you use this pattern, your typography becomes "fluid." If a user triggers a split-screen multitasking event or rotates their device, the onLayout event fires again. The component receives the new, updated width, recalculates the fontSize, and the text reflows gracefully.

By tying your typography to the container, you stop thinking about "phone vs. tablet" and start thinking about "available space." This leads to designs that feel native to any layout configuration, whether it's a full-screen display or a tiny widget within a complex dashboard.

Key Takeaway: By using the onLayout event to capture container dimensions, you can programmatically scale text to maintain perfect visual hierarchy within any layout context.