Highlight Popover

Introduction

A headless React component that shows a popover when people select text.

HighlightPopover watches for text selections inside its children and renders your popover next to the selected text. You write the popover's markup and styles. The component decides when to show it, where to place it, and when to hide it. It has no dependencies besides React.

This is a sample text. Try selecting some words to see the popover in action, then use the button or press Escape to close it.

Installation

npm i @omsimos/react-highlight-popover

Requires React 18 or 19. The build starts with a "use client" directive, so you can render the component directly from a Next.js Server Component.

Usage

Wrap the content people can select, and return your popover from renderPopover:

import { HighlightPopover } from "@omsimos/react-highlight-popover";

export function Article() {
  return (
    <HighlightPopover
      offset={{ y: 8 }}
      renderPopover={({ selection }) => (
        <div className="rounded-sm border bg-white p-2 shadow-lg">
          You selected: {selection}
        </div>
      )}
    >
      <p>
        This is a sample text. Try selecting some words to see the popover in
        action.
      </p>
    </HighlightPopover>
  );
}

To read the selection or close the popover from inside it, use the useHighlightPopover hook:

import {
  HighlightPopover,
  useHighlightPopover,
} from "@omsimos/react-highlight-popover";

function Popover() {
  const { currentSelection, setShowPopover } = useHighlightPopover();

  return (
    <div className="rounded-md border bg-white p-2 shadow-lg">
      <p>You selected: {currentSelection}</p>
      <button onClick={() => setShowPopover(false)}>Close</button>
    </div>
  );
}

export function Article() {
  return (
    <HighlightPopover renderPopover={() => <Popover />} offset={{ y: 8 }}>
      <p>Select some text in this paragraph.</p>
    </HighlightPopover>
  );
}

Next steps

On this page