Tue. Aug 9th, 2022

Development in React involves defining reusable components and assembling them in different parts of your application to achieve the desired user interface (UI). In this article we look at react-textfit library, making it easy to create responsive React components that appear predictably no matter where they appear in a layout.

The problem of text alignment

Because React components are part of JavaScript code that describes a specific section of your user interface, they are virtually independent of each other. And their visual styles are often embedded in them as part of their definition. This can be quite useful as they are likely to be used in different places and layout.

But there are also some drawbacks to integrating styles into a recyclable component. An example is seen in the case of responsiveness. Say you want a line of text – e.g. A headline – to fill the space reserved for it, completely in terms of height and width, but not to wrap it – all without having to write custom CSS rules for any possible situation. (Examples of where you might want this include business slogans, advertising messages, or text embedded in navigation bar components.)

Responsive React Components: Each component you create can have more than one function

CSS and portability

While defining the style of your responsive React component, you will want to consider the size, layout, or style of each overall component that can be wrapped to fit the font size accordingly. As you can imagine, it is not really profitable to take all possible container sizes into account – even if you could do it with CSS. You would chase too many viewport scenarios for it to be convenient to write media queries. But apart from media queries, there is not really a way in CSS to ensure that a block of text will always fit within a single line.

Create recyclable React components

Fortunately, some React libraries can be easily used to solve this problem. They allow you to define recyclable React components where text behaves as expected, regardless of which container the recyclable component is placed in. At the end of this article, you can use these libraries to tackle the aforementioned text alignment problem and make a component that can be recycled. So let’s take a look at everything you need to know to make your text automatically fit into the space available in React.

First, we will look at why such a problem is so important and why common solutions may not be enough, especially when using React. Then, react-textfit React library will be presented and used to implement a solution for both single and multi-line text.

Responsive React Components: Each component you create has properties for different environments

Text alignment problem in reusable components

Let’s look at the following demo that explains the text customization issue with an example.

See the pen
Text-alignment problem with SitePoint (@SitePoint)
on CodePen.

The goal is to make a headline fit the space reserved for it, regardless of the size of the user’s screen. In this example, viewport devices are used to define font-size for the headline. Consequently, while the size of the red border changes iframe represents the user’s screen, the headline always matches its parent <div>. So this method certainly allows the headline text to adapt to any screen width. However, is Headline component in style can not be reused. This is because it is designed with only this particular text in mind. By adding to the headline text or resizing the parent <div>, the text will no longer fit on a line. (You can experiment with changing the text in the demo.) We really want a recyclable component to be more flexible than this.

As mentioned, another solution of CSS media queries is offered, which allows you to customize your text size according to the screen size. This is the ideal solution when considering the web page as a whole. But it is not practical to chase an infinite number of possible container widths with media requests. This would result in a lot of work. Plus, and would make your components much less portable.

react-textfit as a solution to Responsive React Text

So let’s see how react-textfit React library makes it possible to automatically adapt text to the available space, which really makes the component reusable.

See the pen
Text-fit problem with react-textfit by SitePoint (@SitePoint)
on CodePen.

As you can see, they have the aforementioned issues. Thanks to react-textfit, you can now change the header or resize the parent <div>, while your headline is close to the free space.

How Textfit working

Let us now see in detail how react-textfit working.

As stated on the project’s official GitHub page, react-textfit is a library for mounting headings and sections in all recyclable components. It effectively finds the correct fit and works with any CSS style configuration, e.g. padding, line-height, etc.

You can add it to your dependencies by launching the following command:

npm install react-textfit --save

Then you get access to Textfit component that matches any text, as follows:

import { Textfit } from 'react-textfit';

Textfit will be translated into one <div> HTML element, and allows you to fit both single-line and multi-line text in any reusable component or HTML element.

To use it, you only need to wrap text in the following way:

  Sample text

Or any HTML element that contains the following:

  <span>Sample text</span>

Since Textfit is a <div>, you can pass CSS rules to it via React style plug, as follows:

  style={{"width": "200px"}}
  Sample text

Or by assigning it to a CSS class through className, as follows:

  Sample text

Textfit props

Textfit also comes with a few props that can be used to fit your text as desired. Let’s see them all:

  • mode is a string that can assume two values: single or multi. It defines the method the component uses to fit the text. That single mode should be used for headings, and multi section mode. The default value is multi.
  • min is a number that represents the smallest font size that the text can reach in pixels. The default value is 1.
  • max is a number that represents the maximum font size that the text can reach in pixels. The default value is 100.
  • forceSingleModeWidth is a boolean used only below single state to make Textfit component ignores the height of the element completely. The default value is true.
  • throttle is a number that represents the window for changing the throttle in milliseconds. The default value is 50.
  • onReady is a function called when the text is appropriate.

Two of the most important are min and max, which allows you to specify lower and upper limits for font size, respectively. Then there is mode plug, which defines how Textfit component must behave. This requires a more detailed explanation. So let’s see both modes in action.

How to customize text with a line in reusable components

Single-line text is represented by headings, titles, and labels. It is usually contained in <h1>, <h2>, <h3>or more generally <p> and <span> HTML elements. When processing text with a line, the appropriate problem is almost inevitable. This is because its font size tends to be much larger than that used in paragraphs. When single mode is activated by the above mode prop i Textfit, the following algorithm is used, involving a mandatory and an optional step:

1. binary search to fit the element's width
2. if forceSingleModeWidth=false and text overflows height
    2a. binary search to also fit the element's height

As explained here, the binary search algorithm is used to retrieve the correct font size to make the text in Textfit component fits its width. So if forceSingleModeWidth is set to false, the same procedure is used – but also taking into account the height of the element.

Make a React component recyclable: a single-line demo

Now let’s see Textfit single mode in action through a live demo:

See the pen
react-textfit single-line demo by SitePoint (@SitePoint)
on CodePen.

As you can see, by making your text longer, its font size is updated accordingly by Textfit to make it fit its size. The exact same logic is used to resize the text box while keeping the text constant. This is what would happen with smaller screens. So, Textfit represents the perfect solution for making headlines and titles responsive in any React component or HTML element.

How to customize multi-line text in responsive responses

Multiline text is represented by paragraphs, subtitles and descriptions. It is usually contained in <p>, <em>, or <div> HTML elements. The fit problem with multi-line text is frequent in terms of height. In fact, when your text deals with smaller screens, your text gets taller due to the reduced width. As a result, this may cause your text to exceed fixed height maps or sections.

When multi mode is activated in Textfit, the following algorithm is used, which involves two mandatory steps:

1. binary search to fit the element's height
2. if text overflows width
    2a. binary search to also fit the element's width

The binary search algorithm is used to retrieve the correct font size to create the text in Textfit component fits its height. Then the same procedure is used, but also taking into account the width of the element. As you can see, unlike what happens in single condition, the height has priority over the width. This is explained by the reason presented above.

Make a React component recyclable: a multi-line demo

Now let’s see Textfit multi mode in action through a live demo:

See the pen
react-textfit multi-line demo by SitePoint (@SitePoint)
on CodePen.

By interacting with the live demo and making your multi-line text longer, its font size is updated to fit the HTML element dimension. The same thing happens by changing the size of Textfit component, while the text is constant. This is what will happen with smaller screens. So, Textfit is a great solution for making paragraphs and long descriptions responsive in any HTML element or React component.

Responsive React components: components will be presented with different div sizes


As smartphones and tablets have become the most widely used devices used to access the Internet, responsiveness has become an issue that can no longer be overlooked. In this article, we have looked at a specific issue on this domain. In particular, we have examined a specific text alignment issue, why it is so important to tackle, and how to do it in React.

That react-textfit library is a useful, open, efficient React library that allows you to easily make your text — both single-line and multi-line — fit any React component effortlessly. I hope you found the explanation and demos useful. Thanks for reading! Feel free to contact me with questions, comments or suggestions.

Leave a Reply

Your email address will not be published.