Home > Back-end >  Highlighting text (user input)
Highlighting text (user input)

Time:05-07

I'm trying to involve coding a simple component to highlight substrings of text provided by a user

but I'm getting errors when I'm trying to get the value from a text-area and compare it against a input area

import React from "react";

const Highlighted = ({ text = "", highlight = "" }) => {
  if (!highlight.trim()) {
    return <span>{text}</span>;
  }
  const regex = new RegExp(`(${highlight})`, "gi");
  const parts = text.split(regex);

  return (
    <span>
      {parts.filter(String).map((part, i) => {
        return regex.test(part) ? (
          <mark key={i}>{part}</mark>
        ) : (
          <span key={i}>{part}</span>
        );
      })}
    </span>
  );
};

const App = () => {
  const text = <textarea data-testid="source-text" />;
  const highlight = <input data-testid="search-term" />;
  return (
    <>
      <Highlighted
      text={text}
      highlight={highlight}
    />
    </>
  );
};

export default App;

CodePudding user response:

const text = <textarea data-testid="source-text" />;
const highlight = <input data-testid="search-term" />;

You cannot get values directly from JSX.

Instead of doing that, you can set useState for those variables (as states), and use onChange on these input fields for updating the states with input values.

const Highlighted = ({ text = "", highlight = "" }) => {
  if (!highlight.trim()) {
    return <span>{text}</span>;
  }
  const regex = new RegExp(`(${highlight})`, "gi");
  const parts = text.split(regex);

  return (
    <span>
      {parts.filter(String).map((part, i) => {
        return regex.test(part) ? (
          <mark key={i}>{part}</mark>
        ) : (
          <span key={i}>{part}</span>
        );
      })}
    </span>
  );
};

const App = () => {
  const [text, setText] = React.useState('')
  const [highlight, setHighlight] = React.useState('')
  return (
    <div>
    <textarea data-testid="source-text" onChange={(event) => setText(event.target.value)}/>
    <input data-testid="search-term" onChange={(event) => setHighlight(event.target.value)}/>
    <Highlighted
      text={text}
      highlight={highlight}
    />
    </div>
  );
};

ReactDOM.render(
  <App/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Related