A lightweight React component that wraps the browser-native CSS Custom Highlight API for performant text highlighting without DOM manipulation.
- Zero DOM churn – highlights render via browser paint layers
- Composable ranges – stack multiple highlight keys with independent styles
- Search integration – built-in hook for live query updates
- Design-token friendly – style via CSS custom properties
- Accessible – preserves document structure and screen-reader flow
- TypeScript ready – full type safety with comprehensive definitions
pnpm dlx shadcn@latest add text-highlighterThe CLI copies the component into your project so you can customize it directly.
Add these CSS rules to your global stylesheet:
/* globals.css */
::highlight(default) {
background-color: #fef08a;
color: inherit;
}
::highlight(primary) {
background-color: #93c5fd;
color: inherit;
}import { TextHighlighter } from "@/components/ui/text-highlighter";
import { useState } from "react";
function SearchableContent() {
const [searchTerm, setSearchTerm] = useState("");
return (
<div>
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search..."
/>
<TextHighlighter searchTerm={searchTerm} highlightKey="default">
<p>Your content here will be highlighted as you search.</p>
</TextHighlighter>
</div>
);
}import { TextHighlighter } from "@/components/ui/text-highlighter";
import { useTextHighlight } from "@/hooks/use-text-highlight";
function AdvancedSearch() {
const {
searchTerm,
setSearchTerm,
caseSensitive,
setCaseSensitive,
matchCount,
} = useTextHighlight();
return (
<div>
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={caseSensitive}
onChange={(e) => setCaseSensitive(e.target.checked)}
/>
Case sensitive ({matchCount} matches)
</label>
<TextHighlighter
searchTerm={searchTerm}
caseSensitive={caseSensitive}
highlightKey="primary"
>
<div>Your searchable content...</div>
</TextHighlighter>
</div>
);
}Visit the live documentation for:
- Interactive examples
- Complete API reference
- Advanced usage patterns
Requires the CSS Custom Highlight API:
- Chrome/Edge 105+
- Safari 17.2+
- Firefox 130+
# Clone the repo
git clone https://github.com/junaidanjum/text-highlight.git
cd text-highlight
# Install dependencies
pnpm install
# Start development server
pnpm devContributions are welcome! Please read CONTRIBUTING.md before opening a pull request.
MIT © Junaid Anjum
Developed by Junaid Anjum