Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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 Respuestas
Responde la pregunta

0

Why are you not using useCallback as shown in the recipe

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda