React
penciled/react is the React adapter of penciled.org: a hook and a component that let readers highlight text and add notes in React, without wrapping text in spans. They wrap annotate(), creating the instance when the component mounts and destroying it when it unmounts. React 18 and later are supported.
How do I highlight selected text in React without wrapping it in spans?
Section titled “How do I highlight selected text in React without wrapping it in spans?”Wrap the content in <Annotatable>, or pass a ref to useAnnotations(). penciled paints highlights with the CSS Custom Highlight API, so no <span> or <mark> is added to the markup React owns, and React can re-render the annotated content as often as it likes. Highlights stay in place.
Why do mark.js highlights disappear after a React re-render?
Section titled “Why do mark.js highlights disappear after a React re-render?”Because mark.js changes the DOM behind React’s back. It wraps matches in <mark> elements, and when React re-renders that part of the tree it restores the markup it expects, dropping the <mark> elements, or it fails because the text nodes it tracked were split. Re-running mark.js after every render works around it, but you’re still fighting React for the same nodes. Highlights painted with the CSS Custom Highlight API have no elements for React to remove. For highlighting search terms, mark.js is still the better fit; see the comparison.
<Annotatable>
Section titled “<Annotatable>”The quickest way: wrap your content.
import { Annotatable } from 'penciled/react';import 'penciled/styles.css';
export function Article({ post }) { return ( <Annotatable as="article" options={{ documentId: post.id }}> <h1>{post.title}</h1> <div dangerouslySetInnerHTML={{ __html: post.html }} /> </Annotatable> );}as sets the element to render (div by default). Other props, such as className, are passed to it. To reach the instance, pass a ref as instanceRef:
import { Annotatable, type Annotator } from 'penciled/react';import { useRef } from 'react';
export function Article({ children }) { const annotations = useRef<Annotator | null>(null); return ( <> <button onClick={() => annotations.current?.clear()}>Clear highlights</button> <Annotatable instanceRef={annotations}>{children}</Annotatable> </> );}useAnnotations()
Section titled “useAnnotations()”The hook annotates the element in a ref you provide, and returns the instance, or null before it is ready.
import { useAnnotations } from 'penciled/react';import { useRef, useState } from 'react';
export function Article({ post }) { const ref = useRef<HTMLElement>(null); const [count, setCount] = useState(0); const annotations = useAnnotations(ref, { documentId: post.id, onLoad: (all) => setCount(all.length), onCreate: () => setCount((n) => n + 1), onDelete: () => setCount((n) => n - 1), });
return ( <> <p> {count} highlights <button onClick={() => annotations?.clear()}>Clear</button> </p> <article ref={ref}>{/* … */}</article> </> );}How options update
Section titled “How options update”The instance is created once, so not every option can change on the fly:
- Changing
documentIdorreadOnlydestroys the instance and creates a new one. themeapplies immediately, throughsetTheme().- The
on…callbacks always call their latest version, so inline functions are fine. - Other options are read when the instance is created. To apply a change, remount the component, for example with a
key:
<Annotatable key={colors.join()} options={{ colors }}> {children}</Annotatable>How do I add text annotations to a Next.js App Router app?
Section titled “How do I add text annotations to a Next.js App Router app?”Put the annotated content in a client component, and pass server-rendered content into it as children. Importing penciled/react on the server is safe, and the instance is only created in the browser, in an effect, so this works in the App Router, the Pages Router and other SSR frameworks.
'use client';
import { Annotatable } from 'penciled/react';import type { ReactNode } from 'react';
export function AnnotatedArticle({ id, children }: { id: string; children: ReactNode }) { return ( <Annotatable as="article" options={{ documentId: `post:${id}` }}> {children} </Annotatable> );}import { AnnotatedArticle } from './annotated-article';import { getPost } from '@/lib/posts';
export default async function Page({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await getPost(slug); return ( <AnnotatedArticle id={post.id}> <h1>{post.title}</h1> <div dangerouslySetInnerHTML={{ __html: post.html }} /> </AnnotatedArticle> );}import 'penciled/styles.css';The page stays a server component; only AnnotatedArticle runs in the browser. Set documentId to something that identifies the content, like the post’s id: client-side navigation then gives each post its own annotations, and changing documentId creates a new instance. To save highlights per user, pass a storage adapter in options.
Showing annotations in React
Section titled “Showing annotations in React”Annotations live in the instance, not in React state. To render them, for example in a list of notes, copy them into state from the events:
import type { Annotation, Annotator } from 'penciled';import { useEffect, useState } from 'react';
function useAnnotationList(annotations: Annotator | null) { const [list, setList] = useState<Annotation[]>([]); useEffect(() => { if (!annotations) return; const sync = () => setList(annotations.getAll()); annotations.ready.then(sync); const offs = ['create', 'update', 'delete'].map((e) => annotations.on(e as 'create', sync)); return () => offs.forEach((off) => off()); }, [annotations]); return list;}Each item can call annotations.focus(item.id) to scroll to it and open it.