0.1.1 • Published 9 months ago

react-custom-highlight v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

React Custom Highlight

npm version NPM License NPM Downloads

React hook for highlighting text ranges on a document (see Custom Highlight API).

⚠️ Warning

This package is based on the Custom Highlight API, which may not be supported by some browsers.

Installation

npm install react-custom-highlight
yarn add react-custom-highlight

Usage

To use it, just provide hook's ref to target container and add ::highlight pseudo-element.

// App.tsx
import { useState } from "react";
import { createRoot } from "react-dom/client";
import { useCustomHighlight } from "react-custom-highlight";
import "./App.css";

function App() {
  const [text, setText] = useState("");
  const ref = useCustomHighlight({ name: "app", text }, [text]);

  return (
    <div>
      <input
        placeholder="Enter search text here..."
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <article ref={ref}>
        <h1>Lorem ipsum dolor sit amet</h1>
        <p>
          Lorem ipsum dolor sit amet
          <span>Lorem ipsum dolor sit amet.</span>
        </p>
      </article>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);

// App.css
::highlight(app) {
  color: red;
}

And the hook will mark all occurrences of text parameter within the container. Add params to dependency array for recalculation (if needed).

Props

PropertyTypeRequired?Description
textString+Search text to be highlighted in container
nameString+Name of specified ::highlight pseudo-element
isDeferredBooleanText value should be wrapped with useDeferredValue. Defaults to true
isDebugModeBooleanDebug mode flag for inspecting errors. Defaults to false
isCaseSensitiveBooleanSearch should be case sensitive. Defaults to false
shouldResetOnUnmountBooleanHighlights should be cleared on hook container unmount. Defaults to true
nodeFilter(node: Node) => numberFunction to filter nodes for avoid highlights (see NodeFilter). Omitted by default

License

MIT.

0.1.1

9 months ago

0.1.0

9 months ago