react-truncate-inside

react-truncate-inside is a React component that truncates text in the middle with an ellipsis, so a long string such as a file name, hash or wallet address keeps both its beginning and its end visible. The middle ellipsis is placed by measuring the real rendered width, and it is recomputed when the container resizes.

react-truncate-inside demo: a file name truncated in the middle as its container is resized

Features

When to use

Use middle truncation whenever the end of a string carries information: an extension, a checksum suffix, the last characters that tell two similar values apart. The number of characters kept at the end is set with offset; how many characters of the start survive depends on the available width.

Use caseOriginalTruncatedoffset
File namesECMA-402_9th_edition_june_2022.pdfECMA-402_9th...2022.pdf8
Hashesa94a8fe5ccb19ba61c4c0873d391e987982fbbd3a94a8fe5cc...2fbbd36
Wallet addresses0x71C7656EC7ab88b098defB751B7401B5f6d8976F0x71C7656E...976F4
URLshttps://example.com/docs/guides/getting-started/installationhttps://example.com/do...installation12
File paths/Users/alice/Projects/client/src/components/Header.tsx/Users/alice/Proj...Header.tsx10

Install

npm install react-truncate-inside
# or
yarn add react-truncate-inside
# or
pnpm add react-truncate-inside

Quick start

import React from 'react';
import Truncate from 'react-truncate-inside';

export default function Demo() {
  return <Truncate text="An-Extremely-Long-Filename.pdf" width={100} />;
}

Renders a 100 px wide element containing something like An-...name.pdf; how many leading characters survive depends on the font.

Examples

TypeScript

The default export is typed, and the props interface is exported as TruncateProps.

import React from 'react';
import Truncate from 'react-truncate-inside';
import type { TruncateProps } from 'react-truncate-inside';

type FileNameProps = Pick<TruncateProps, 'width'> & { name: string };

export function FileName({ name, width }: FileNameProps) {
  // Keep the extension plus a few characters in front of it.
  return <Truncate text={name} width={width} offset={8} />;
}

Fill the parent and follow its width

Omit width and the element takes the full width of its parent. A ResizeObserver re-truncates the text whenever that width changes, for example when a sidebar is dragged or the window is resized.

function Sidebar({ fileName }) {
  return (
    <aside style={{ width: '20vw' }}>
      <Truncate text={fileName} />
    </aside>
  );
}

Show the full text on hover

The component renders a single div and does not forward extra attributes, so put the title on a wrapper element.

function FileLabel({ fileName }) {
  return (
    <span title={fileName}>
      <Truncate text={fileName} width={160} />
    </span>
  );
}

In a table cell

Give the column a width (or use table-layout: fixed). With automatic table layout the cell grows to fit the full text, so there is nothing to truncate.

function FileTable({ files }) {
  return (
    <table style={{ tableLayout: 'fixed', width: '100%' }}>
      <colgroup>
        <col style={{ width: '60%' }} />
        <col style={{ width: '40%' }} />
      </colgroup>
      <tbody>
        {files.map((file) => (
          <tr key={file.id}>
            <td>
              <Truncate text={file.name} />
            </td>
            <td>{file.size}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Props

NameTypeDefaultDescription
textstringrequiredThe text to display.
widthnumberparent width (100%)Width of the element in px. When omitted the element fills its parent and re-truncates whenever the parent is resized.
offsetnumber8Number of characters kept at the end of the text. The ellipsis is inserted this many characters from the end.
ellipsisstring'...'String inserted where characters were removed. Only present when the text is actually truncated.

The component renders <div style="width: <width>px or 100%; white-space: nowrap"> with the (possibly truncated) text as its only child.

How it works

The component renders the text in a div with white-space: nowrap and measures it with an off-screen <canvas> 2D context whose font is set to the element's computed font. If the text is wider than the element, a binary search finds the longest prefix such that prefix + ellipsis + last offset characters still fits. It measures again whenever the element is resized, the width or text props change, or document.fonts reports that web fonts have finished loading.

Limitations worth knowing:

Comparison

ApproachEllipsis positionAdapts to widthNotes
react-truncate-insideMiddle, keeping the last offset charactersYes (ResizeObserver)Single line only. About 1 kB, zero dependencies, TypeScript types included.
CSS text-overflow: ellipsisEnd only (or start, with direction: rtl)Yes, nativelyNo JavaScript, works with any font feature. The right choice when hiding the end of the text is acceptable.
react-truncateEnd; can clamp to several linesYesCovers multi-line "read more" style truncation, which this library does not do.
Hand-written measuring codeAnywhere you chooseIf you implement itFull control. You handle font measurement, resize, web font loading, code points and server rendering yourself.

FAQ

Why not just use CSS text-overflow: ellipsis?

Because CSS can only put the ellipsis at the end of the text (or at the start with direction: rtl); there is no middle position, so a file extension or the end of an address is the first thing to disappear. Use CSS when the end of the text is not important, and a middle truncation component when it is.

Does it update when the container resizes?

Yes. The element observes its own size with a ResizeObserver and re-truncates whenever the width changes, including when the parent is resized by a drag handle or a window resize. Changing the width or text props also triggers a new measurement.

Does it work with SSR / Next.js?

Yes. During server rendering the component outputs the full text and does not touch document or window; the truncation is computed in the browser in a layout effect right after mount, before the first paint. No dynamic import or ssr: false is needed.

Can I keep the file extension visible?

Yes, that is what offset is for: it is the number of characters kept at the end of the text, 8 by default. For .pdf or .png files the default already keeps the extension plus four characters in front of it; raise it for longer extensions such as .tar.gz or when the end of the string needs more context.

Why is my text not truncated inside a table?

Because with automatic table layout the cell expands to fit the full text, so the element never overflows. Set table-layout: fixed and give the column a width, or put the component in a cell with an explicit max-width.

Does it support multiple lines?

No. The component is single-line (white-space: nowrap). For multi-line clamping with an ellipsis at the end, use CSS -webkit-line-clamp or a library such as react-truncate.

License

MIT License. Author: zhiyuc123.