Menu

Components

Show More

Keeps long content short until the reader asks for the rest, with a button that opens it.

Introduction

Show More clips long content, a description, a review, a list of tags, to a few lines and puts a button under it that opens the rest. The page stays short, and the reader chooses whether to read on.

  • Clip by lines, for text, or by height in pixels, for lists and blocks. Or make it horizontal, to clip one line by its width and open it sideways.
  • It measures the content and shows the button only when something is hidden. Short content is shown in full, with no button.
  • It follows the content: when the width changes and the text wraps differently, or an image loads, it measures again.
  • The last line fades out while it is closed, and the button is a link or a Button. It opens with a transition, and without one for people who prefer reduced motion.
  • The button has aria-expanded and points to the content with aria-controls. Clipped text is still in the page, so screen readers read all of it.

The fade goes to the page color. On a different background, set --show-more-fade on a parent, for example [--show-more-fade:var(--card)] inside a card.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports. It also needs Button and the icons.

1. Add the styles

src/types/show-more-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for ShowMore: a box that clips its content to a height (or, when it is
// horizontal, a width), a fade at the far edge that hints there is more, and the
// button that opens it. The box is resized with a CSS transition on
// `max-height` or `max-width`, between two pixel values the component measures.
export const showMoreStyles = tv({
  slots: {
    root: "flex",
    box: "relative overflow-hidden duration-300 ease-out motion-reduce:transition-none",
    fade: "pointer-events-none absolute from-[var(--show-more-fade,var(--bg))] to-transparent transition-opacity duration-300 motion-reduce:transition-none",
    link: "inline-flex items-center gap-1 self-start rounded-sm text-sm font-medium text-fg underline underline-offset-4 outline-none hover:text-muted-fg focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
    chevron:
      "size-4 transition-transform duration-300 motion-reduce:transition-none",
  },
  variants: {
    orientation: {
      vertical: {
        root: "flex-col gap-2",
        box: "transition-[max-height]",
        fade: "inset-x-0 bottom-0 h-[2.5em] bg-linear-to-t",
      },
      // The content stays on one line and is clipped from the right, with the
      // button after it.
      horizontal: {
        root: "flex-row items-center gap-2",
        box: "min-w-0 whitespace-nowrap transition-[max-width]",
        fade: "inset-y-0 right-0 w-[2.5em] bg-linear-to-l",
        link: "shrink-0",
      },
    },
    align: {
      start: { root: "items-start" },
      center: { root: "items-center", link: "self-center" },
      end: { root: "items-end", link: "self-end" },
    },
  },
  defaultVariants: { orientation: "vertical", align: "start" },
});

2. Add the Show More file

src/components/ui/show-more/show-more.tsxShow code
"use client";

import {
  type ReactNode,
  useCallback,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { ChevronDownIcon, ChevronRightIcon } from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { Separator } from "@/components/ui/separator/separator";
import { cn } from "@/lib/cn";
import { showMoreStyles } from "@/types/show-more-styles";

export interface ShowMoreProps {
  /** The content that may be too long: text, a list, anything. */
  children: ReactNode;
  /**
   * The direction it opens in:
   * - `vertical`: the content is clipped from the bottom and opens downward, with
   *   the button under it. The default.
   * - `horizontal`: the content stays on one line, is clipped from the right and
   *   opens sideways, with the button after it. For a row of tags, a path, a
   *   long line. Set `maxWidth` for how much of it shows.
   */
  orientation?: "vertical" | "horizontal";
  /**
   * How many lines to show before the rest is hidden. Counted in the line
   * height of the content, so it suits text. Defaults to 3. Ignored when
   * `maxHeight` is set, and when it is horizontal.
   */
  lines?: number;
  /** Show this many pixels of the content instead of counting lines, for a list or a block. */
  maxHeight?: number;
  /** For a horizontal one, how many pixels of the width show while it is closed. Defaults to 240. */
  maxWidth?: number;
  /** Whether it is open, for a controlled component. */
  isExpanded?: boolean;
  /** Whether it starts open, for an uncontrolled one. Defaults to `false`. */
  defaultExpanded?: boolean;
  /** Called when the user opens or closes it. */
  onExpandedChange?: (isExpanded: boolean) => void;
  /** The text of the button while it is closed. Defaults to "Show more". */
  moreLabel?: string;
  /** The text of the button while it is open. Defaults to "Show less". */
  lessLabel?: string;
  /**
   * Fade the last line of the clipped content into the background, a hint that
   * there is more. It fades to the page color, or to `--show-more-fade`, which
   * you can set on a parent with a different background. Defaults to `true`.
   */
  showFade?: boolean;
  /** The button as a link (an underlined word) or as a `Button`. Defaults to `link`. */
  triggerVariant?: "link" | "button";
  /**
   * A horizontal line on each side of the button, running out to the edges:
   * "—— Show more ——". Off unless set, and it suits the `button` trigger with
   * `isCircle`.
   */
  showSeparator?: boolean;
  /** Round ends on the button, when `triggerVariant` is `button`. */
  isCircle?: boolean;
  /** Where the button sits under the content. Not used by a horizontal one, whose button is beside it. */
  align?: "start" | "center" | "end";
  className?: string;
}

/**
 * Keeps long content short until the reader asks for the rest: a description, a
 * review, a list of tags. It shows the first lines (or the first so many
 * pixels), fades them out, and puts a "Show more" button under them that opens
 * the rest with a smooth transition.
 *
 * It measures the content, so it shows the button only when something is
 * hidden: short content is shown in full with no button. It follows the
 * content as it changes, for example when an image loads.
 *
 * @example
 * <ShowMore lines={3}>
 *   <p>A long description ...</p>
 * </ShowMore>
 */
export function ShowMore({
  children,
  orientation = "vertical",
  lines = 3,
  maxHeight,
  maxWidth = 240,
  isExpanded,
  defaultExpanded = false,
  onExpandedChange,
  moreLabel = "Show more",
  lessLabel = "Show less",
  showFade = true,
  triggerVariant = "link",
  isCircle,
  showSeparator = false,
  align,
  className,
}: ShowMoreProps) {
  const isHorizontal = orientation === "horizontal";
  const styles = showMoreStyles({
    orientation,
    align: isHorizontal ? "center" : align,
  });
  const id = useId();
  const box = useRef<HTMLDivElement>(null);
  const [inner, setInner] = useState(defaultExpanded);
  const expanded = isExpanded ?? inner;
  // The size along the direction it opens in (the height, or the width when it
  // is horizontal) of the clipped box and of all the content, in pixels. Unknown
  // until the first measure, and then the box is clipped by CSS alone.
  const [size, setSize] = useState<{ clipped: number; full: number } | null>(
    null,
  );

  const measure = useCallback(() => {
    const el = box.current;
    if (!el) return;
    // A line is a line of the content, whose text size may differ from the box.
    const style = getComputedStyle(el.firstElementChild ?? el);
    const lineHeight =
      Number.parseFloat(style.lineHeight) ||
      Number.parseFloat(style.fontSize) * 1.5;
    const clipped = isHorizontal ? maxWidth : (maxHeight ?? lines * lineHeight);
    const full = isHorizontal ? el.scrollWidth : el.scrollHeight;
    setSize((current) =>
      current?.clipped === clipped && current.full === full
        ? current
        : { clipped, full },
    );
  }, [isHorizontal, lines, maxHeight, maxWidth]);

  useLayoutEffect(measure, [measure]);

  // Follow the content and the width of the box: text wraps to more lines when
  // it narrows, and images change the height when they load.
  useEffect(() => {
    const el = box.current;
    if (!el) return;
    const observer = new ResizeObserver(measure);
    observer.observe(el);
    for (const child of Array.from(el.children)) observer.observe(child);
    return () => observer.disconnect();
  }, [measure]);

  const hasMore = size !== null && size.full > size.clipped + 1;
  const isOpen = expanded && hasMore;

  function toggle() {
    const next = !expanded;
    if (isExpanded === undefined) setInner(next);
    onExpandedChange?.(next);
  }

  // Until it is measured the box is clipped in CSS: `lh` is one line height.
  const clipped = isHorizontal
    ? `${maxWidth}px`
    : maxHeight !== undefined
      ? `${maxHeight}px`
      : `${lines}lh`;
  const length =
    size === null
      ? clipped
      : !hasMore || expanded
        ? `${size.full}px`
        : `${size.clipped}px`;

  const trigger =
    triggerVariant === "button" ? (
      <Button
        size="sm"
        variant="outline"
        isCircle={isCircle}
        aria-expanded={expanded}
        aria-controls={id}
        onPress={toggle}
      >
        {expanded ? lessLabel : moreLabel}
        {isHorizontal ? (
          <ChevronRightIcon
            className={cn(styles.chevron(), expanded && "rotate-180")}
          />
        ) : (
          <ChevronDownIcon
            className={cn(styles.chevron(), expanded && "rotate-180")}
          />
        )}
      </Button>
    ) : (
      <button
        type="button"
        aria-expanded={expanded}
        aria-controls={id}
        onClick={toggle}
        className={styles.link()}
      >
        {expanded ? lessLabel : moreLabel}
      </button>
    );

  return (
    <div className={cn(styles.root(), className)}>
      <div
        ref={box}
        id={id}
        style={isHorizontal ? { maxWidth: length } : { maxHeight: length }}
        className={styles.box()}
      >
        {children}
        {showFade ? (
          <span
            aria-hidden="true"
            className={cn(
              styles.fade(),
              isOpen || !hasMore ? "opacity-0" : "opacity-100",
            )}
          />
        ) : null}
      </div>
      {hasMore ? (
        showSeparator ? (
          <div
            className={cn(
              "flex min-w-0 items-center gap-3",
              isHorizontal ? "flex-1" : "w-full",
            )}
          >
            <Separator className="min-w-0 flex-1" isDecorative />
            {trigger}
            <Separator className="min-w-0 flex-1" isDecorative />
          </div>
        ) : (
          trigger
        )
      ) : null}
    </div>
  );
}

3. Use it

import { ShowMore } from "@/components/ui/show-more/show-more";

Anatomy

A clipped box, a fade, and a button.

<ShowMore lines={3}>
  {/* any content: text, a list, a block */}
</ShowMore>
PartRendered asNotes
BoxdivClips the content to the lines or the height you set, and opens with a transition.
Fadespan, aria-hiddenFades the last line into the background while the content is closed.
TriggerbuttonShown only when something is hidden. It has aria-expanded and aria-controls.

Examples

Usage

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Orientation

Vertical opens downward, and is the default. Horizontal keeps the content on one line, clips it from the right, and opens sideways, with the button after it. Set maxWidth for how much shows. It suits a row of tags or a long path. It opens as far as there is room, so the content should fit the width of its parent.

Accessible by defaultLight and dark themesKeyboard support

/Users/alwin/code/component/centerui/src/components/ui/show-more

Lines

How many lines show while it is closed. Three by default.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Height

Clip to a height in pixels instead, for a list or a block that has no lines to count.

  • Accessible by default
  • Light and dark themes
  • Keyboard support
  • Copy into your project
  • Tailwind CSS v4
  • TypeScript types
  • Reduced motion support
  • No runtime lock-in

Labels

Say what is behind the button in your own words.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Button and position

The trigger is a link by default, or a button with an arrow. It sits at the start, the center or the end. With showSeparator, a line runs out on each side of it.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Without the fade

Turn the fade off when the background is not one color, or the clipped edge should be plain.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Start open

It can start open, and the reader closes it.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Controlled

Own the state with isExpanded and onExpandedChange, to open it from somewhere else.

centerUI is a set of components you copy into your project and own. Each one is built on react-aria for behavior and accessibility, styled with Tailwind, and follows your theme in light and dark. There is no package to update and no hidden layer: the code is yours to read, change and grow. Start with the pieces you need, and add the rest when you do.

Closed

Short content

When everything fits, nothing is hidden and there is no button.

A short note.

Component API

ShowMore takes the props below.

PropTypeDefault
childrenReactNode-
orientation"vertical" | "horizontal""vertical"
linesnumber3
maxHeightnumber (px)-
maxWidthnumber (px)240
isExpandedboolean-
defaultExpandedbooleanfalse
onExpandedChange(isExpanded: boolean) => void-
moreLabelstring"Show more"
lessLabelstring"Show less"
showFadebooleantrue
triggerVariant"link" | "button""link"
isCirclebooleanfalse
showSeparatorbooleanfalse
align"start" | "center" | "end""start"
classNamestring-