---
title: "Outline — React"
description: "Show a document's outline (its bookmarks) as a tree, follow its items, mark where the reader is, and let people add, rename, move and delete items."
framework: "React"
source: "https://www.embedpdf.com/docs/headless/react/documents/outline"
---

# Outline

A document's outline is its table of contents: titled items, nested, each going to a place in the
document. Acrobat calls the items bookmarks. Register `outlinePlugin()` to show it in your UI:

**`outline-list.tsx`**

```tsx
import { useOutline, useOutlineState } from '@embedpdf/react/outline';

export function OutlineList() {
  const outline = useOutline();
  const { rows, current } = useOutlineState();

  return (
    <ul role="tree">
      {rows.map(({ item, depth, hasChildren, expanded }) => (
        <li
          key={item.ref.objectNumber}
          role="treeitem"
          aria-level={depth + 1}
          aria-expanded={hasChildren ? expanded : undefined}
          aria-current={item.ref.objectNumber === current?.objectNumber ? 'location' : undefined}
          style={{ paddingInlineStart: depth * 16 }}
        >
          {hasChildren && (
            <button onClick={() => outline.toggle(item.ref)}>{expanded ? '▾' : '▸'}</button>
          )}
          <button onClick={() => outline.activate(item.ref)}>{item.title}</button>
        </li>
      ))}
    </ul>
  );
}
```

What `useOutlineState()` gives you updates by itself: after your own changes, and on a shared
document, after someone else's. Nothing is read when a document opens: the outline loads the first
time something asks for it, so a document nobody shows the outline of costs nothing.

## Show the outline

`rows` are the rows a tree shows: every item whose parents are all expanded, depth first. Each row
has the `item`, its `depth` (0 at the top level), `hasChildren`, and whether it's `expanded`.
`items` is every item, folded or not, when you'd rather build the tree yourself.

`toggle(ref)` folds or unfolds an item; `expand(ref)`, `collapse(ref)`, `expandAll()` and
`collapseAll()` do one of them. The items the file opens start expanded, and from then on what's
expanded is the reader's: it doesn't change the document.

An item has its `title`, its `color` (`null` when the file sets none, so draw your own text
colour), and whether it's `bold` or `italic`. `status` says whether the outline hasn't been asked
for yet (`'idle'`), is loading, is there (`'ready'`), or couldn't be read. `incomplete` is `true`
when part of the outline couldn't be read, such as a loop in a damaged file; what could be read is
listed.

## Follow an item

`activate(ref)` goes where the item goes, as a click does: a page moves the view, a website opens,
and an item that runs a script runs it, through the [actions plugin](https://www.embedpdf.com/docs/headless/react/documents/actions)
when you've registered it. It returns what happened at once, so a website can still open from the
reader's click.

`current` is the item for where the reader is: the last item, in reading order, that goes to a place
at or above the top of the view. Mark its row, and the reader always sees where they are in the
outline:

```ts
const isCurrent = row.item.ref.objectNumber === current?.objectNumber;
```

**`bookmarks.tsx`**

```tsx
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStageState } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { outlinePlugin, useOutline, useOutlineState } from '@embedpdf/react/outline';
import { localEngine } from '@embedpdf/engine';

import './bookmarks.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), outlinePlugin()];

const welcome = async (): Promise<OpenInput> => {
  const response = await fetch('/pdfs/welcome.pdf');
  return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// Bookmarks the reader adds: each one goes to the place in view when it's added.
function Bookmarks() {
  const outline = useOutline();
  const { rows, current, selected, canEdit } = useOutlineState();
  const { currentPageIndex } = useStageState();
  const selectedNumber = selected[0]?.objectNumber;

  return (
    <aside className="bookmarks">
      <header className="bookmarks-header">
        <h3 className="bookmarks-title">Bookmarks</h3>
        <button
          type="button"
          className="button primary"
          disabled={!canEdit}
          onClick={() =>
            outline.create({ title: `Page ${currentPageIndex + 1}` }, { select: true })
          }
        >
          Add
        </button>
      </header>
      {rows.length === 0 ? (
        <p className="empty">Scroll to a page, then add a bookmark.</p>
      ) : (
        <ul className="list">
          {rows.map(({ item }) => {
            const number = item.ref.objectNumber;
            return (
              <li
                key={number}
                className="row"
                data-current={number === current?.objectNumber || undefined}
                data-selected={number === selectedNumber || undefined}
              >
                <button
                  type="button"
                  className="row-title"
                  onClick={() => {
                    outline.select([item.ref]);
                    outline.activate(item.ref);
                  }}
                >
                  {item.title}
                </button>
                <button
                  type="button"
                  className="row-delete"
                  aria-label={`Delete ${item.title}`}
                  disabled={!canEdit}
                  onClick={() => outline.delete([item.ref])}
                >
                  ×
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </aside>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: welcome }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <div className="layout">
          <Bookmarks />
          <Stage className="stage">{() => <RenderLayer />}</Stage>
        </div>
      </DocumentGate>
    </Viewer>
  );
}
```

**`bookmarks.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #3858e9;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The bookmarks beside the pages */
.layout {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 14px;
}

.bookmarks {
  display: flex;
  flex-direction: column;
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--surface);
  box-shadow: 0 1px 2px var(--shadow);
  overflow: hidden;
}

.bookmarks-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px 10px 14px;
  border-bottom: 1px solid var(--line);
}

.bookmarks-title {
  margin: 0;
  font-size: 13px;
  font-weight: 650;
  color: var(--ink);
}

.empty {
  margin: 0;
  padding: 18px 14px;
  font-size: 12.5px;
  color: var(--muted);
}

/* One row per bookmark: the one being read is marked, the picked one tinted */
.list {
  margin: 0;
  padding: 6px;
  list-style: none;
  overflow-y: auto;
}

.row {
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 8px;
}

.row[data-selected] {
  background: var(--tint);
}

.row[data-current]::before {
  content: '';
  position: absolute;
  inset: 6px auto 6px 0;
  width: 3px;
  border-radius: 3px;
  background: var(--accent);
}

.row-title {
  flex: 1;
  min-width: 0;
  font: inherit;
  font-size: 13px;
  text-align: start;
  color: var(--ink);
  background: none;
  border: 0;
  padding: 7px 10px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.row-delete {
  font: inherit;
  font-size: 16px;
  line-height: 1;
  color: var(--muted);
  background: none;
  border: 0;
  border-radius: 6px;
  padding: 4px 8px;
  cursor: pointer;
  opacity: 0;
}

.row:hover .row-delete,
.row-delete:focus-visible {
  opacity: 1;
}

.row-delete:hover {
  color: var(--ink);
  background: var(--line);
}

.button {
  font: inherit;
  font-size: 12px;
  font-weight: 600;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 6px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

.button.primary {
  color: #ffffff;
  background: var(--accent);
  border-color: var(--accent);
}

.button:focus-visible,
.row-title:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled,
.row-delete:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Change the outline

`create()` adds an item. Leave out where it goes and it goes to the place in view; leave out its
title and it takes the selected text, or "Untitled" in the viewer's language. It shows at once, and
`select: true` selects it and unfolds the items it sits under, so it's ready to rename:

```ts
await outline.create({ parent: chapter.ref, position: 'end' }, { select: true });
```

`update(ref, changes)` changes the fields you pass: a `title`, a `target`, a `color`, `bold`,
`italic`, or `open` (whether it's expanded when the document opens). `null` removes a target or a
colour. `move(refs, parent, position)` moves items, with the items under them, to their new place,
and `delete(refs)` deletes items with the items under them.

Each of these shows at once, is one step to undo, and resolves once the engine has it. A place is
a neighbour, not a number: `'start'`, `'end'`, `{ before: ref }` or `{ after: ref }` among the
parent's children.

**`nesting.tsx`**

```tsx
import { useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { outlinePlugin, useOutline, useOutlineState } from '@embedpdf/react/outline';
import type { OutlineItem, OutlineItemRef } from '@embedpdf/react/outline';
import { localEngine } from '@embedpdf/engine';

import './nesting.css';

const engine = localEngine();
const plugins = [outlinePlugin()];

const welcome = async (): Promise<OpenInput> => {
  const response = await fetch('/pdfs/welcome.pdf');
  return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const same = (left: OutlineItemRef | null, right: OutlineItemRef | null) =>
  left?.objectNumber === right?.objectNumber;

/** The picked item, the one before it among its parent's children, and its parent. */
const neighboursOf = (items: readonly OutlineItem[], picked: OutlineItemRef | undefined) => {
  const item = items.find((each) => same(each.ref, picked ?? null)) ?? null;
  if (!item) return { item, previous: null, parent: null };
  const siblings = items.filter((each) => same(each.parent, item.parent));
  const previous = siblings[siblings.indexOf(item) - 1] ?? null;
  const parent = items.find((each) => same(each.ref, item.parent)) ?? null;
  return { item, previous, parent };
};

// An outline being built: add items, nest them, fold them, rename and delete them.
function OutlineEditor() {
  const outline = useOutline();
  const { items, rows, selected, canEdit } = useOutlineState();
  const [title, setTitle] = useState('Chapter');
  const [picked] = selected;
  const { item, previous, parent } = neighboursOf(items, picked);

  // After the picked item, or at the end.
  const add = (inside: boolean) =>
    outline.create(
      inside && item
        ? { title, parent: item.ref }
        : { title, parent: item?.parent ?? null, position: item ? { after: item.ref } : 'end' },
      { select: true },
    );

  const indent = () => {
    if (!item || !previous) return;
    outline.move([item.ref], previous.ref, 'end');
    outline.expand(previous.ref);
  };

  const outdent = () => {
    if (item && parent) outline.move([item.ref], parent.parent, { after: parent.ref });
  };

  return (
    <div className="editor">
      <div className="toolbar">
        <input
          className="field"
          value={title}
          aria-label="Title"
          onChange={(event) => setTitle(event.target.value)}
        />
        <button type="button" className="button" disabled={!canEdit} onClick={() => add(false)}>
          Add
        </button>
        <button
          type="button"
          className="button"
          disabled={!canEdit || !item}
          onClick={() => add(true)}
        >
          Add inside
        </button>
        <button type="button" className="button" disabled={!canEdit || !previous} onClick={indent}>
          Indent
        </button>
        <button type="button" className="button" disabled={!canEdit || !parent} onClick={outdent}>
          Outdent
        </button>
        <button
          type="button"
          className="button"
          disabled={!canEdit || !item}
          onClick={() => item && outline.update(item.ref, { title })}
        >
          Rename
        </button>
        <button
          type="button"
          className="button"
          disabled={!canEdit || !item}
          onClick={() => item && outline.delete([item.ref])}
        >
          Delete
        </button>
      </div>
      {rows.length === 0 ? (
        <p className="empty">This document has no outline yet. Add an item.</p>
      ) : (
        <ul className="tree" role="tree">
          {rows.map(({ item: row, depth, hasChildren, expanded }) => (
            <li
              key={row.ref.objectNumber}
              className="row"
              role="treeitem"
              aria-level={depth + 1}
              aria-expanded={hasChildren ? expanded : undefined}
              aria-selected={row.ref.objectNumber === picked?.objectNumber}
              style={{ paddingInlineStart: 6 + depth * 18 }}
            >
              <button
                type="button"
                className="chevron"
                aria-label={expanded ? 'Collapse' : 'Expand'}
                disabled={!hasChildren}
                data-expanded={expanded || undefined}
                onClick={() => outline.toggle(row.ref)}
              ></button>
              <button
                type="button"
                className="row-title"
                onClick={() => {
                  outline.select([row.ref]);
                  setTitle(row.title);
                }}
              >
                {row.title}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: welcome }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <OutlineEditor />
      </DocumentGate>
    </Viewer>
  );
}
```

**`nesting.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --accent: #3858e9;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The title to add or rename with, and what to do with the picked item */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.field {
  width: 160px;
  font: inherit;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 10px;
}

.field:focus {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

.button {
  font: inherit;
  font-size: 12px;
  font-weight: 600;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:focus-visible,
.chevron:focus-visible,
.row-title:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

/* The tree: each level indented, a parent with a chevron that folds it */
.tree {
  margin: 0;
  padding: 6px;
  list-style: none;
  min-height: 220px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--surface);
  box-shadow: 0 1px 2px var(--shadow);
}

.row {
  display: flex;
  align-items: center;
  gap: 2px;
  border-radius: 8px;
}

.row[aria-selected='true'] {
  background: var(--tint);
}

.chevron {
  display: grid;
  place-items: center;
  width: 22px;
  height: 22px;
  color: var(--muted);
  background: none;
  border: 0;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.15s ease;
}

/* Drawn rather than typed, so it's the same size in every font: a right-pointing chevron */
.chevron::before {
  content: '';
  width: 6px;
  height: 6px;
  border-right: 1.5px solid currentColor;
  border-bottom: 1.5px solid currentColor;
  transform: translateX(-1px) rotate(-45deg);
}

.chevron:disabled {
  visibility: hidden;
}

.chevron[data-expanded] {
  transform: rotate(90deg);
}

.row-title {
  flex: 1;
  min-width: 0;
  font: inherit;
  font-size: 13px;
  text-align: start;
  color: var(--ink);
  background: none;
  border: 0;
  padding: 7px 8px;
  cursor: pointer;
}

.empty {
  margin: 0;
  padding: 18px;
  font-size: 12.5px;
  color: var(--muted);
  border: 1px dashed var(--line-strong);
  border-radius: 14px;
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Select items

`select(refs)` makes items the selection, and `selected` lists them. The selection is the
reader's, like what's expanded: show it, and act on it with your own buttons.

```ts
outline.select([row.item.ref]);
await outline.delete(selected);
```

## Methods

Everything `useOutline()` gives you.

| Method                         | What it does                                                                                               |
| :----------------------------- | :--------------------------------------------------------------------------------------------------------- |
| `get(ref)`                     | One item, or `null`.                                                                                       |
| `getChildren(parent)`          | An item's children in order, or the top level's for `null`.                                                |
| `isExpanded(ref)`              | Whether an item's children show. [Show the outline](#show-the-outline)                                     |
| `toggle(ref)`                  | Folds an expanded item, unfolds a folded one.                                                              |
| `expand(ref)`, `collapse(ref)` | Unfolds or folds one item.                                                                                 |
| `expandAll()`, `collapseAll()` | Unfolds or folds every item.                                                                               |
| `reveal(ref)`                  | Unfolds every item `ref` sits under, so its row shows.                                                     |
| `select(refs)`                 | Makes these items the selection; `[]` clears it. [Select items](#select-items)                             |
| `activate(ref)`                | Goes where the item goes, as a click does, and returns what happened. [Follow an item](#follow-an-item)    |
| `getCurrentViewTarget()`       | Where the view is, as a target: the page at its top and the spot at its top-left. What a new item goes to. |
| `create(item, options)`        | Adds an item; `select: true` selects it. Resolves `{ item }`. [Change the outline](#change-the-outline)    |
| `update(ref, changes)`         | Changes the fields you pass; `null` removes a target or a colour. Resolves `{ item }`.                     |
| `move(refs, parent, position)` | Moves items, with the items under them, to their new place.                                                |
| `delete(refs)`                 | Deletes items with the items under them, as one change.                                                    |
| `ensureLoaded()`               | Reads the outline from the file, unless it's loaded or loading. Resolves once it's there.                  |
| `refresh()`                    | Reads the outline again. Rarely needed: it stays up to date by itself.                                     |

Every method that returns a promise also takes a `signal` in its options, to cancel it.

## State

Everything `useOutlineState()` gives you. Your component re-renders when a value changes. The method in the last column reads the same value once.

| Field        | What it is                                                                                    | Read once          |
| :----------- | :-------------------------------------------------------------------------------------------- | :----------------- |
| `items`      | Every item, depth first, with your changes shown before the engine answers                    | `list()`           |
| `rows`       | The rows a tree shows: `item`, `depth`, `hasChildren`, `expanded`                             | `listRows()`       |
| `current`    | The item for where the reader is, or `null`                                                   | `getCurrentItem()` |
| `selected`   | The selected items, in the order they were selected                                           | `getSelected()`    |
| `status`     | `'idle'` until something asks for it, then `'loading'`, `'ready'`, `'forbidden'` or `'error'` | `getStatus()`      |
| `incomplete` | Part of the outline couldn't be read                                                          | `isIncomplete()`   |
| `canEdit`    | Whether changing the outline is allowed                                                       | `canEdit()`        |

## Events

**`outline-changed.tsx`**

```tsx
import { useState } from 'react';
import { useOutlineEvent } from '@embedpdf/react/outline';

export function OutlineNotice() {
  const [notice, setNotice] = useState('');

  useOutlineEvent(
    (outline) => outline.onChanged,
    ({ type, items, origin }) => {
      if (origin.kind === 'remote') setNotice(`Someone ${type} ${items.length} bookmark(s)`);
    },
  );

  return <p role="status">{notice}</p>;
}
```

| Event        | Fires when                                                                                                                   | Carries                   |
| :----------- | :--------------------------------------------------------------------------------------------------------------------------- | :------------------------ |
| `onChanged`  | Items were created, updated, moved, deleted or restored, by you or by someone else                                           | `type`, `items`, `origin` |
| `onResynced` | The outline was read from the file: the first time it's asked for, after `refresh()`, or to catch up after a lost connection | `outline`                 |

`type` is `'created'`, `'updated'`, `'moved'`, `'deleted'` or `'restored'`, and `items` names the
items it touched; for a delete, the item first, then the items under it.

## Permissions

| Permission           | What it allows                              | Check               |
| :------------------- | :------------------------------------------ | :------------------ |
| `doc.open`           | Reading the outline                         | none: it opened     |
| `doc.outline.modify` | Adding, changing, moving and deleting items | `outline.canEdit()` |

## Good to know

### Expanded, and open

What's expanded is the reader's view, not the document: folding an item doesn't change the file.
An item's `open` is the file's own setting, whether its children show when the document opens, and
the outline starts from it. Change it with `update(ref, { open })`.

### Pages that are gone

Deleting a page doesn't delete the items that go to it: their target reads `unsupported`, and
`activate()` reports it rather than going anywhere. See
[Outline](https://www.embedpdf.com/docs/engine/documents/outline#pages-that-are-gone).

### The ready-made viewer

The viewer's Outline panel is built on this plugin. See
[Panels](https://www.embedpdf.com/docs/viewer/react/customize/panels).
