Dev Helpers
← Back

Highlighted first match

Import and render <HighlightedFirstMatch /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/HighlightedFirstMatch.tsx

import { useState } from "react";

export default function HighlightedFirstMatch({
  text = "Studio notes from the harbour",
}: { text?: string } = {}) {
  const [q, set] = useState("");
  const i = text.toLowerCase().indexOf(q.toLowerCase());
  return (
    <section>
      <label>
        Find
        <input value={q} onChange={(e) => set(e.target.value)} />
      </label>
      <p>
        {i >= 0 && q ? (
          <>
            {text.slice(0, i)}
            <mark>{text.slice(i, i + q.length)}</mark>
            {text.slice(i + q.length)}
          </>
        ) : (
          text
        )}
      </p>
    </section>
  );
}