• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    TypeScript
  • Created almost 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React hook used to fit text in a div

use-fit-text npm version

React hook that iteratively adjusts the font size so that text will fit in a div.

  • checks if text is overflowing by using scrollHeight and offsetHeight
  • recalculates when container is resized (using (polyfilled) ResizeObserver)
  • recalculates when content changes
  • uses binary search; with default options, makes a maximum of 5 adjustments with a resolution of 5% font size from 20-100%
  • < 4 kB minified + gzipped
  • written in TypeScript

Installation

npm install --save use-fit-text

Usage

import React from "react";
import useFitText from "use-fit-text";

function Example() {
  const { fontSize, ref } = useFitText();

  return (
    <div ref={ref} style={{ fontSize, height: 40, width: 100 }}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
  );
}

Demo / example code

API

useFitText(options)

  • Returns an object with the following properties:

    • fontSize (string) - the font size as a string (CSS percent) to be passed as the fontSize property of the style prop of the div
    • ref (React.MutableRefObject<HTMLDivElement>) - the ref to be passed to the ref attribute of the div
  • options (optional) - an object with the following optional properties:

    • logLevel (string, default: info) - one of debug, info, warn, error, or none
    • maxFontSize (number, default: 100) - maximum font size in percent
    • minFontSize (number, default: 20) - minimum font size in percent
    • onFinish ((fontSize: number) => void, default: undefined) - function that is called when resizing finishes. The final fontSize is passed to the function as an argument.
    • onStart (() => void, default: undefined) - function that is called when resizing starts
    • resolution (number, default: 5) - font size resolution to adjust to in percent

Questions

  • Why doesn't it work with Flexbox justify-content: flex-end;? This appears to be a bug with Flexbox. Try using CSS Grid or margin-top: auto;
  • What does the "reached minFontSize = 20 without fitting text" message in the console mean? This means use-fit-text was not able to fit the text using the minFontSize setting of 20. To ensure the text fits, set minFontSize to a smaller value.

Changelog

  • v2.4.0
    • handle case where minFontSize is set larger than the fontSize value needed to fit the text in the div. Log a message to the console in this case.
    • fix final adjustment calcuation
    • add logLevel option to control what is logged to the console
  • v2.3.0
    • automatically recalculate font size when content changes
    • fix bug where a recalculation was not done on resize if the text initially fit in the div
  • v2.2.0 - add onStart and onFinish callbacks
  • v2.1.3 - export TOptions TypeScript type
  • v2.1.2 - remove /// <reference types="next" /> in dist/index.d.ts
  • v2.1.0
    • fix SSR/prerender issue where text did not resize
    • suppress useLayoutEffect warning for server render
  • v2.0.0
    • use ResizeObserver to always recalculate on container resize
    • remove recalcOnResize option
    • useLayoutEffect instead of useEffect to avoid flashing
  • v1.2.1 - fix scrollbar issue in example
  • v1.2.0 - add recalcOnResize and other options
  • v1.1.0 - fix binary search bug
  • v1.0.2 - add example
  • v1.0.0 - initial release

More Repositories

1

live-log-analyzer

Real-time (Nginx, PHP, syslog, "mysqladmin extended") log file analysis and plotting using Python, mongoDB, Orbited, and flot
JavaScript
126
star
2

flow-cheatsheet

Script to generate a Flow type cheat sheet
Python
65
star
3

kage

Yet another task manager built with Firebase, Next.js, React, Redux, styled-components, Reactstrap, Flow, and Prettier
JavaScript
55
star
4

retry-decorator

Decorator to retry calling a function upon error
Python
46
star
5

flask-jquery-ajax-example

AJAX example using jQuery and Flask
Python
42
star
6

typescript-cheatsheet

Script to generate a TypeScript cheat sheet
Python
33
star
7

subset-sum

Four examples solving a subset sum (knapsack-like) problem
Python
30
star
8

django-trace

A django plugin for tracing code execution
Python
17
star
9

trace-tools

A decorator used for tracing Python code execution
Python
17
star
10

remote-tools

Tools for remote server administration using SSH and Python
Python
12
star
11

graphene-relay-pagination-example

An example GraphQL pagination API for Relay using Graphene and Django + a Next.js React UI
Python
11
star
12

react-chained-modals-comparison

A comparison of approaches for building a sequence of chained modals using React, React Router, Redux, Redux Thunk and Redux Saga
CSS
10
star
13

session-timeout-example

Bank style session timeout example
HTML
9
star
14

react-debounced-props

React higher order component that allows debouncing component updates
JavaScript
9
star
15

homedir

dotfiles, scripts, etc in home directory
Python
8
star
16

react-learning

Code from various React, Redux, Webpack, etc tutorials
JavaScript
8
star
17

flask-encryptedsession

Flask encrypted cookie session
Python
6
star
18

flask-subdomaindevserver

Local development server that uses a different configuration based on the subdomain of the request
Python
6
star
19

redux-promise-memo

"memoization" for promise-based Redux action creators
JavaScript
6
star
20

.spacemacs.d

Emacs spacemacs config
Emacs Lisp
4
star
21

emacs

My .emacs.d directory - No longer current. New config: https://github.com/saltycrane/.spacemacs.d
Emacs Lisp
4
star
22

django-foreign-key-across-db-testproject

Python
4
star
23

django-extras

Python
3
star
24

flask-principal-example

Python
3
star
25

flask-subdomain-dispatcher-example

See https://github.com/saltycrane/flask-subdomaindevserver instead
Python
3
star
26

next-server-side-rollbar-example

Example Next.js server-side Rollbar error reporting
TypeScript
3
star
27

css-cheat-sheets

A Node.js React script to generate a static CSS width cheat sheet HTML file
HTML
2
star
28

debug-tools

Enhanced print statements
Python
2
star
29

soap-suds-chrome-ads-wsdl-stuff

Failing and successful examples using suds with Chrome ADS SUDS service
Python
2
star
30

typescript-react-static-render-script

Node.js script using TypeScript and React to render a static HTML page
TypeScript
2
star
31

immer-use-reducer-typescript-example

TypeScript
1
star
32

django-foreign-key-string-argument

Python
1
star
33

wmii-scripts

Python scripts for controlling the wmii window manager
Python
1
star
34

pillow-issue-example

Example for a Pillow issue
Python
1
star
35

next-storybook-typescript-example

HTML
1
star
36

aphrodite-to-css-modules-codemod

jscodeshift codemod to convert from Aphrodite to CSS Modules
TypeScript
1
star
37

aws-cli-and-docker

Docker image with `amazon/aws-cli` and `docker` installed for CI/CD pipelines
Dockerfile
1
star
38

recoil-vs-context-grid-test

Code used for comparing performance of a spreadsheet-like grid using Recoil vs. React Context
HTML
1
star