Skip to main content

useTextSelection

function useTextSelection(ref?: RefObject<Element | null>): TextSelection;

interface TextSelection {
readonly text: string;
readonly rect: DOMRect | null;
}

Returns the text the user has selected and its bounding box in the viewport, and re-renders as the selection changes, such as to show a "quote" button beside it. Given a ref, only the part of the selection inside that element counts, so a selection elsewhere gives no text. It is { text: "", rect: null } when nothing is selected and on the server, and it stops listening on unmount.

Live demo​

Select a sentence below to quote it.

A bee visits about two million flowers to make one jar of honey.

Example​

import { useRef } from "react";
import { useTextSelection } from "react-honey-hooks";

function Article({ body }: { body: string }) {
const article = useRef<HTMLElement>(null);
const { text, rect } = useTextSelection(article);

return (
<>
<article ref={article}>{body}</article>
{rect && (
<QuoteButton
text={text}
style={{ position: "fixed", top: rect.top - 40, left: rect.left }}
/>
)}
</>
);
}