Truncate a list of elements with a symbol or component of your choice.
- no opinionated styles - fully customizable
- < 1kb bundle size
- SSR friendly
Note: StackBlitz WebContainers may not work in Safari.
View Live Demo Works in all browsers.
Have you ever needed to make something like the design below?
This is surprisingly hard to accomplish, as there is no way to know ahead of time how many items can fit within the space available. This is a low-level library to give you the tools necessary to make this a breeze.
- Add the
react-truncate-listpackage
npm i react-truncate-list- If your project targets older browsers, add the
resize-observer-polyfillpackage to support theResizeObserverAPI (https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).
npm i resize-observer-polyfill- Import the package and its required CSS and use it 🚀
import { TruncatedList } from "react-truncate-list";
import "react-truncate-list/dist/styles.css";This library simply provides an unstyled <ul> that will render a component of your choice after the last item that fits within it before overflowing. It is up to you to provide a max-height or some other constraint on its dimensions so that it will experience overflow behaviour.
Please see the interactive demo for concrete examples for how the library can be used. As this is a low-level library, it takes a little more work than you may be used to. However this will empower you to customise the list to look and behave exactly as you need.
type RenderTruncatorFn = (state: { hiddenItemsCount: number }) => React.ReactNode;
type OnResizeFn = (bag: { truncate: () => void }) => void;
type Props = {
renderTruncator: RenderTruncatorFn;
alwaysShowTruncator?: boolean;
onResize?: OnResizeFn
className?: string;
style?: React.CSSProperties;
children?: React.ReactNode;
};A render function called to display a 'truncator' after the last item before overflowing the container.
renderTruncator={({ hiddenItemsCount }) => (
<span>{hiddenItemsCount} more items...</span>
)}
Pass the list items as children. Each child will be automatically wrapped in an <li>.
Always show the 'truncator', even when all items are visible. Useful for advanced use-cases such as an expanding list.
Pass a callback for when the list resizes. You can use this to debounce the truncating effect for performance reasons, If you use this, you must manually call the provided truncate() function in your callback.
See the Debounced truncation example in the demo.
Before hydration, the list will have overflow: auto applied to it so that it is scrollable. Once hydrated in the client, a layout effect will fire, shortening the list and inserting the 'truncator'.
- Install dependencies
npm install- Start the development server
npm run devThis will start the library sandbox. Changes to the library will be reflected instantly.
