npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@hazembraiek/react-text-highlight

v0.0.5-beta

Published

<div align="center"> <img src="https://dl.dropboxusercontent.com/scl/fi/uw8egqxrme5kpdhkjdexa/1764693415455_1740222307936-New-svg.svg?rlkey=rkii4v4a8v8jwnvd5qfomdkse&dl=0" alt="React Text Highlight Logo" width="150" height="150" />

Downloads

473

Readme

React Text Highlight

A powerful, flexible, and easy-to-use React component for highlighting text. Perfect for search features, documentation sites, and content management systems.

npm version npm downloads license

Demo | NPM | GitHub


Video Demo

See React Text Highlight in action:

Can't see the video? Click here to watch the demo or visit the live demo site


Features

  • Multiple search terms - Highlight multiple words at once
  • Case-sensitive matching - Optional case-sensitive search
  • Exact word matching - Match whole words only
  • Custom styling - Full control over highlight appearance
  • Click handlers - Interact with highlighted text
  • Tooltips - Built-in tooltip support
  • TypeScript ready - Full type definitions included
  • Zero config - Works out of the box with sensible defaults
  • Lightweight - Minimal dependencies
  • React 18 & 19 - Compatible with latest React versions

Installation

npm install @hazembraiek/react-text-highlight
yarn add @hazembraiek/react-text-highlight
pnpm add @hazembraiek/react-text-highlight

Quick Start

import { TextHighlight } from "@hazembraiek/react-text-highlight";

function App() {
  return (
    <TextHighlight
      text="React Text Highlight makes it easy to highlight text in your applications"
      highlightWords={["React", "highlight", "text"]}
    />
  );
}

Basic Examples

Simple Highlighting

<TextHighlight
  text="The quick brown fox jumps over the lazy dog"
  highlightWords={["quick", "fox", "lazy"]}
/>

Case-Sensitive Search

<TextHighlight
  text="React is awesome. react makes development easy."
  highlightWords={["React"]}
  caseSensitive={true}
/>

Exact Word Matching

<TextHighlight
  text="This is a test. Testing is important."
  highlightWords={["test"]}
  exactWord={true}
  // Will match "test" but not "Testing"
/>

Custom Styling

<TextHighlight
  text="Highlight this text with custom colors"
  highlightWords={["Highlight", "custom"]}
  highlightStyle={{
    backgroundColor: "#ffeb3b",
    color: "#000",
    fontWeight: "bold",
    padding: "2px 4px",
    borderRadius: "3px",
  }}
/>

With Click Handler

<TextHighlight
  text="Click on any highlighted word"
  highlightWords={["Click", "highlighted", "word"]}
  onHighlightClick={(e, word, index) => {
    console.log(`Clicked: ${word} at index ${index}`);
  }}
/>

Track Match Count

function SearchComponent() {
  const [matchCount, setMatchCount] = useState(0);

  return (
    <div>
      <p>Found {matchCount} matches</p>
      <TextHighlight
        text="Search text to find matches in this text"
        highlightWords={["text", "matches"]}
        onHighlightCountChange={setMatchCount}
      />
    </div>
  );
}

API Reference

Props

Required Props

| Prop | Type | Description | | ---------------- | ---------- | --------------------------------------------- | | text | string | The text content to display and search within | | highlightWords | string[] | Array of words/phrases to highlight |

Optional Props

| Prop | Type | Default | Description | | --------------- | ---------- | ------- | ----------------------------------------------- | | caseSensitive | boolean | false | Enable case-sensitive matching | | exactWord | boolean | false | Match whole words only (word boundaries) | | autoEscape | boolean | true | Escape special regex characters in search terms | | sanitize | boolean | true | Sanitize HTML in text content | | ignoreWords | string[] | [] | Words to exclude from highlighting |

Styling Props

| Prop | Type | Default | Description | | ---------------------- | -------------------- | --------------------------------------------------- | ------------------------------------------- | | highlightStyle | CSSProperties | { backgroundColor: 'yellow', fontWeight: 'bold' } | Inline styles for highlighted text | | highlightClassName | string | '' | CSS class for highlighted text | | highlightTag | string \| function | 'mark' | HTML tag or custom component for highlights | | unhighlightStyle | CSSProperties | {} | Inline styles for non-highlighted text | | unhighlightClassName | string | '' | CSS class for non-highlighted text | | unhighlightTag | string \| function | 'span' | HTML tag for non-highlighted text | | className | string | '' | CSS class for wrapper element | | style | CSSProperties | {} | Inline styles for wrapper element | | wrapperTag | string | 'div' | HTML tag for wrapper element |

Advanced Props

| Prop | Type | Default | Description | | -------------------------- | --------- | ------------------------------- | ---------------------------------------- | | ellipsis | boolean | false | Enable text ellipsis for overflow | | enableAutoScroll | boolean | true | Auto-scroll to active highlight | | activeHighlightClassName | string | 'react-text-highlight-active' | CSS class for currently active highlight |

Callback Props

| Prop | Type | Description | | -------------------------- | ------------------------------ | ---------------------------------------------- | | onHighlightClick | (event, word, index) => void | Called when a highlighted word is clicked | | onHighlightCountChange | (count) => void | Called when the number of matches changes | | onCurrentHighlightChange | (index) => void | Called when the active highlight index changes |

Tooltip Props

| Prop | Type | Description | | ----------------- | --------------------- | ------------------------------- | | tooltip | object | Tooltip configuration object | | tooltip.enabled | boolean | Enable/disable tooltips | | tooltip.content | (text) => ReactNode | Custom tooltip content renderer |

Ref Methods

Access component methods using a ref:

import { useRef } from "react";
import { TextHighlight } from "@hazembraiek/react-text-highlight";

function MyComponent() {
  const highlightRef = useRef(null);

  const goToNext = () => {
    highlightRef.current?.next();
  };

  const goToPrevious = () => {
    highlightRef.current?.previous();
  };

  return (
    <div>
      <button onClick={goToPrevious}>Previous</button>
      <button onClick={goToNext}>Next</button>
      <TextHighlight
        ref={highlightRef}
        text="Navigate through highlighted words"
        highlightWords={["Navigate", "highlighted", "words"]}
      />
    </div>
  );
}

Available Ref Methods

  • next() - Navigate to next highlighted word
  • previous() - Navigate to previous highlighted word

Advanced Usage

Custom Highlight Component

<TextHighlight
  text="Custom component for each highlight"
  highlightWords={["Custom", "highlight"]}
  highlightTag={(word, index, props) => (
    <strong
      {...props}
      style={{ ...props.style, color: "blue" }}
      data-index={index}
    >
      {word}
    </strong>
  )}
/>

With Tooltips

<TextHighlight
  text="Hover over highlighted words to see tooltips"
  highlightWords={["Hover", "highlighted", "tooltips"]}
  tooltip={{
    enabled: true,
    content: (text) => `You clicked: ${text}`,
  }}
/>

Ignore Specific Words

<TextHighlight
  text="Highlight all words except the ignored ones"
  highlightWords={["all", "words", "the", "ones"]}
  ignoreWords={["the"]}
  // Will highlight "all", "words", "ones" but not "the"
/>

Multiple Styling Classes

// In your CSS
.custom-highlight {
  background: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 600;
}

// In your component
<TextHighlight
  text="Beautiful gradient highlights"
  highlightWords={['Beautiful', 'gradient', 'highlights']}
  highlightClassName="custom-highlight"
/>

Real-World Search Example

function SearchableContent() {
  const [searchTerm, setSearchTerm] = useState("");
  const [matchCount, setMatchCount] = useState(0);

  const content = `
    React is a JavaScript library for building user interfaces.
    It makes creating interactive UIs painless.
    Design simple views for each state in your application.
  `;

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p>{matchCount} matches found</p>
      <TextHighlight
        text={content}
        highlightWords={searchTerm.split(" ").filter(Boolean)}
        onHighlightCountChange={setMatchCount}
        highlightStyle={{
          backgroundColor: "#ffeb3b",
          padding: "2px 4px",
          borderRadius: "3px",
        }}
      />
    </div>
  );
}

TypeScript

The package includes full TypeScript definitions. Import types as needed:

import {
  TextHighlight,
  TextHighlightProps,
  TextHighlightRef,
} from "@hazembraiek/react-text-highlight";

const MyComponent: React.FC = () => {
  const ref = useRef<TextHighlightRef>(null);

  const props: TextHighlightProps = {
    text: "TypeScript support included",
    highlightWords: ["TypeScript", "support"],
  };

  return <TextHighlight {...props} ref={ref} />;
};

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • React 18+
  • React 19+

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT © Hazem Braiek

Links

Support

If you find this package helpful, please consider:


Made with ❤️ by Hazem Braiek