# Dynamic Text Resizing

> This code implements a React component that dynamically adjusts the font size of text to perfectly fit within its parent container.  It solves the common problem of text overflowing its boundaries, ensuring readability regardless of screen size or container dimensions. The component uses a binary search algorithm to efficiently determine the optimal font size.   Here's how it works:  1. **Initialization:** The component uses `useRef` to access the container and text elements directly.  `useEffect` adds a resize listener to the window, triggering a font size recalculation whenever the window is resized. 2. **`resizeText` Function:** This function performs a binary search to find the largest font size that prevents text overflow. It starts with a minimum and maximum font size.  It iteratively calculates the midpoint, sets the text's font size, and checks if it overflows. If it does not overflow, it increases the minimum; otherwise, it decreases the maximum. This continues until the optimal size is found. 3. **Rendering:** The component renders a div acting as the container and a span holding the text.  The `ref` attributes link these elements to the `useRef` hooks. 4. **Cleanup:** The `useEffect` hook's return function removes the resize event listener when the component unmounts, preventing memory leaks.  This component is useful in various scenarios where text needs to adapt to different screen sizes or container widths, such as headers, titles, or responsive layouts. For instance, imagine a hero section with a title that should always be visible and readable without overflowing, regardless of the user's screen size. This component will ensure that the title text always fits perfectly within the available space.  Key Concepts and Libraries: - React: Used for building the user interface. - `useRef`: For accessing DOM elements directly. - `useEffect`: For managing side effects like event listeners. - Binary Search: An efficient algorithm for finding the optimal font size.

- Author: [Sonu](https://21st.dev/@uniquesonu)
- License: unknown
- Live preview: https://21st.dev/@uniquesonu/components/dynamic-text-resizing

## Install

```bash
npx shadcn@latest add "https://21st.dev/r/uniquesonu/dynamic-text-resizing?api_key=$API_KEY_21ST"
```

Requires a 21st API key (generate one at https://21st.dev/mcp) passed as `API_KEY_21ST`. Free accounts get a limited number of installs per day; unlimited on a paid plan — see https://21st.dev/pricing.

Full component directory: https://21st.dev/llms.txt
