Create Responsive React Components with React Textfit


Developing in React involves defining reusable components and assembling them into various parts of your application to achieve your desired user interface (UI). In this article, we’ll look at the react-textfit library, which makes it easy to create responsive React components that display predictably wherever they appear in a layout.

The Text-fitting Issue

Since React components are pieces of JavaScript code describing a particular section of your UI, they’re virtually independent of each other. And their visual styles are often embedded within them, as part of their definition. This can be quite helpful, given that they’re likely to be used in different locations and layouts.

But there are also some downsides to embedding styles within a reusable component. One example is seen in the case of responsiveness. Say you want a line of text — such as a heading — to completely fill the space reserved for it in terms of height and width, but not to wrap — all without having to write custom CSS rules for every possible situation. (Examples of where you might want this include business slogans, advertisement messages, or text embedded in navbar components.)

CSS and portability

While defining the style of your responsive React component, you’d want to take into account the size, layout, or style of each possible parent component that might wrap it to adapt the font size accordingly. As you can imagine, taking every possible container size into account isn’t really viable — even if you could do it with CSS. You’d be chasing far too many viewport scenarios for it to be practical to write media queries. But other than media queries, there isn’t really a way in CSS to ensure that a block of text will always fit within a single line.

Create reusable React components

Thankfully, some React libraries can be used to address this issue effortlessly. They allow you to define reusable React components where text behaves as expected regardless of the container the reusable component is placed in. By the end of this article, you’ll be able to use of these libraries to tackle the aforementioned text fitting problem and make a component reusable. So, let’s take a look at everything you should know to make your text automatically fit the available space in React.

First, we’ll look at why facing such a problem is so important and why common solutions may not be enough, especially when using React. Then, the 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 will properties for different environments

Text Fitting Problem in Reusable Components

Let’s take a look at the following demo explaining the text fitting problem with an example.

See the Pen
Text fitting problem
by 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 units are used to define the font-size for the headline. Consequently, while resizing the red-bordered iframe representing the user’s screen, the headline will always fit its parent <div>. So this method certainly allows the headline text to adapt to any screen width. However, the Headline styled component is not reusable. This is because it’s 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 one line. (You can experiment with changing the text in the demo.) We really want a reusable component to be more adaptable than this.

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

react-textfit as a Solution for Responsive React Text

So let’s see how the react-textfit React library makes it possible to automatically fit text within the available space, truly making the component reusable.

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

As you can see, the aforementioned issues have. Thanks to react-textfit, you can now change the headline or resize the parent <div>, while keeping your headline snugly fitting the available space.

How Textfit works

Now, let’s see in detail how react-textfit works.

As stated in the official GitHub page of the project, react-textfit is a library for fitting headlines and paragraphs in any reusable components. It efficiently finds the correct fit and works with any CSS style configuration, such as padding, line-height, and so on.

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

npm install react-textfit --save

Then you’ll be able to access the Textfit component to fit any text, as follows:

import { Textfit } from 'react-textfit';

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

To use it, you only make it wrap text, as follows:

<Textfit>
  Sample text
</Textfit>

Or any HTML element containing, as follows:

<Textfit>
  <span>Sample text</span>
</Textfit>

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

<Textfit
  style={{"width": "200px"}}
>
  Sample text
</Textfit>

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

<Textfit
  className={"divWidth200"}
>
  Sample text
</Textfit>

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 used by the component to fit the text. The single mode should be used for headlines, and the multi mode for paragraphs. The default value is multi.
  • min is a number representing the minimum font size the text is allowed to reach in pixels. The default value is 1.
  • max is a number representing the maximum font size the text is allowed to reach in pixels. The default value is 100.
  • forceSingleModeWidth is a Boolean that’s used only during single mode to make the Textfit component ignore the element’s height completely. The default value is true.
  • throttle is a number representing the window resize throttle in milliseconds. The default value is 50.
  • onReady is a function that’s called whenever the text is fit.

Two of the most important ones are min and max, which allow you to set lower and upper bounds in terms of font size respectively. Then there’s the mode prop, which defines how the Textfit component should behave. This requires a more detailed explanation. So, let’s see both modes in action.

How to Fit Single-line Text in Reusable Components

Single-line text is represented by headlines, titles, and labels. It’s usually contained in <h1>, <h2>, <h3>, or in more general <p> and <span> HTML elements. When dealing with single-line text, the fitting problem is almost unavoidable. This is because its font size tends to be much bigger than the one used in paragraphs. When the single mode is activated by the aforementioned mode prop in Textfit, the following algorithm involving a mandatory and an optional step is applied:

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 right font size to make the text contained in the Textfit component fit its width. Then, if forceSingleModeWidth is set to false, the same approach is used — but also taking into account the element’s height.

Making a React component reusable: a single-line demo

Now, let’s see the 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 will be updated accordingly by Textfit to make it match its size. The exact same logic is applied when resizing the text box while maintaining the text constant. This is what would happen with smaller screens. So, Textfit represents the perfect solution to make headlines and title responsive in any React component or HTML element.

How To Fit Multi-line Text in Responsive React Components

Multi-line text is represented by paragraphs, subtitles, and descriptions. It is usually contained in <p>, <em>, or <div> HTML elements. The fitting problem with multi-line text is frequent in terms of height. In fact, when dealing with smaller screens, your text will become taller because of the reduced width available. As a result, this might make your text exceed cards or sections with fixed height.

When the multi mode is activated in Textfit, the following algorithm involving two mandatory steps is applied:

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 right font size to make the text contained in the Textfit component fit its height. Then, the same approach is used, but also taking into account the element’s width. As you can see, as opposed to what happens in the single mode, height has priority over width. This is explained by the reason presented above.

Making a React component reusable: a multi-line demo

Now, let’s see the 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 will be updated to make the text fit the HTML element dimension. The same thing happens when resizing the Textfit component while maintaining the text constant. This is what will happen with smaller screens. So, Textfit is a good solution to make paragraphs and long descriptions responsive in any HTML element or React component.

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

Conclusion

Since smartphones and tablets have become the most widely used devices used for accessing the Web, responsiveness has become a problem that can no longer be overlooked. In this article, we’ve looked at a specific problem in this domain. In particular, we’ve explored a particular text fitting problem, why it’s so important to tackle, and how to do it in React.

The react-textfit library is a useful, open-source, effective 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 reach out to me with any questions, comments, or suggestions.



Source link