How to Create Responsive React Components with React Textfit

Share this article

How to 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.)

Responsive React components: each component you create may have more than one function

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.

Frequently Asked Questions (FAQs) about Responsive React Components – TextFit

What is the primary function of the TextFit component in React?

The TextFit component in React is primarily used to make text responsive. It automatically adjusts the font size based on the width and height of its container. This is particularly useful in responsive web design where the layout needs to adapt to different screen sizes. The TextFit component ensures that the text remains readable and aesthetically pleasing regardless of the device or screen size.

How do I install the TextFit component in my React project?

You can install the TextFit component in your React project using npm (Node Package Manager). Open your terminal, navigate to your project directory, and run the following command: npm install react-textfit --save. This will add the TextFit component to your project’s dependencies.

How do I use the TextFit component in my React application?

After installing the TextFit component, you can import it into your React component using the following line of code: import TextFit from 'react-textfit';. You can then use the TextFit component in your render method like any other React component. For example: <TextFit mode="single" max={40}>This is some text</TextFit>.

What are the different modes available in the TextFit component?

The TextFit component offers two modes: ‘single’ and ‘multi’. The ‘single’ mode adjusts the font size so that the entire text fits on a single line. The ‘multi’ mode allows the text to wrap onto multiple lines, adjusting the font size so that all the text fits within the container.

Can I set a maximum and minimum font size in the TextFit component?

Yes, you can set a maximum and minimum font size in the TextFit component using the ‘max’ and ‘min’ props respectively. For example: <TextFit mode="single" min={10} max={40}>This is some text</TextFit>.

How does the TextFit component handle overflow?

The TextFit component automatically prevents text overflow by adjusting the font size. If the text cannot fit within the container at the minimum specified font size, the TextFit component will truncate the text and add an ellipsis.

Can I use the TextFit component with other React components?

Yes, the TextFit component can be used with other React components. You can nest other components within the TextFit component, or use the TextFit component within other components.

Is the TextFit component compatible with all browsers?

The TextFit component is compatible with all modern browsers that support React and CSS3. This includes Chrome, Firefox, Safari, Edge, and Internet Explorer 9 and above.

Can I use the TextFit component in a server-side rendered React application?

Yes, the TextFit component can be used in a server-side rendered React application. However, since the TextFit component relies on the DOM to calculate the font size, it will not adjust the font size until the component is mounted on the client side.

How do I troubleshoot issues with the TextFit component?

If you encounter issues with the TextFit component, you can check the console for any error messages. These messages can provide clues about what might be causing the issue. If you can’t resolve the issue, you can seek help from the React community or the maintainers of the TextFit component.

Antonello ZaniniAntonello Zanini
View Author

I'm a software engineer, but I prefer to call myself a Technology Bishop. Spreading knowledge through writing is my mission.

react componentsstyling React components
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week