Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
React-pdf "Highlight text on the page" is not working

I am trying to implement React-pdf pdf highlighting feature:

import React, { useMemo, useState } from 'react';
// import { Document, Page } from 'react-pdf';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';

import samplePDF from './test.pdf';

// https://gist.github.com/wojtekmaj/f265f55e89ccb4ce70fbd2f8c7b1d95d
function highlightPattern(text, pattern) {
  const splitText = text.split(pattern);

  if (splitText.length <= 1) {
    return text;
  }

  const matches = text.match(pattern);

  return splitText.reduce((arr, element, index) => (matches[index] ? [
    ...arr,
    element,
    <mark key={index}>
      {matches[index]}
    </mark>,
  ] : [...arr, element]), []);
}

export default function Test() {
  const [searchText, setSearchText] = useState('');

  // const textRenderer = useMemo((textItem) => {
  //   return highlightPattern(textItem.str, searchText);
  // }, [searchText]);

  function onChange(event) {
    setSearchText(event.target.value);
  }

  return (
    <>
      <Document
        file={samplePDF}
        // onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page
          pageNumber={1}
          // customTextRenderer={textRenderer}
        />
      </Document>
      <div>
        <label htmlFor="search">Search:</label>
        <input type="search" id="search" value={searchText} onChange={onChange} />
      </div>
    </>
  );
}

Please note that I have commented the textRenderer function. If I uncomment it (still the Page component's prop is commented) application is crashed with

TypeError: Cannot read properties of undefined (reading 'str')

Reason could be textItem is null or undefined. But how can I fix this with useMemo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Why are you not using useCallback as shown in the recipe

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!