0

As user types in input field, I want the matching letter in the text to be highlighted in red. So texts displayed is "Hello" and user types in "h" then I would like text to be updated to <span style="color:red">H</span>ello. I'm trying it with vanilla js way, which is createElement span then add style to it then append a letter, but no luck. What is the react way of accomplishing this? https://codesandbox.io/s/msft-machine-coding-react-ts-to9szx?file=/src/App.tsx:0-1613

App.tsx

import React, { useState, useEffect } from "react";
import "./styles.css";
import { posts } from "./data";

let slicedOne = posts.slice(0, 5);
let slicedTwo = posts.slice(5, 10);
let slicedThree = posts.slice(10);

export default function App() {
  const [feeds, setFeeds] = useState([]);
  const [currentView, setCurrentView] = useState(0);
  const [slicedFeeds, setSlicedFeeds] = useState([
    slicedOne,
    slicedTwo,
    slicedThree
  ]);
  const [texts, setTexts] = useState(
    slicedFeeds[currentView].map((feed) => feed.fullText)
  );

  let arr = [];
  const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let copiedTexts = texts;
    for (let text of copiedTexts) {
      for (let i = 0; i < text.length; i++) {
        console.log(text[i]);
        if (text[i].toLowerCase() === e.target.value) {
          console.log("matched");
          let span = document.createElement("span"); // this is not working...
          span.style.color = "red";
          span.append(text[i]);
        }
      }
    }
  };

  return (
    <div>
      <div>
        <input type="text" onChange={handleOnChange} />
      </div>
      {slicedFeeds[currentView].map((feed, idx) => {
        return (
          <div key={feed.dateTimeCreated}>
            {feed.from.name} {feed.dateTimeLastModified}
            <div>{feed.fullText}</div>
            <br></br>
          </div>
        );
      })}
      <div>
        <button onClick={() => setCurrentView(0)}>1</button>
        <button onClick={() => setCurrentView(1)}>2</button>
        <button onClick={() => setCurrentView(2)}>3</button>
      </div>
    </div>
  );
}

data.tsx

export const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hours.Hello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hours",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Viniket",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Bhushan",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Tanvi",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Rahul",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Deeksha",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Swati",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Ketki",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Preksha",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Sonali",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Gagan",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Pratiksha",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Bhagyashree",
      email: "garima@gmail.com"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Milind",
      email: "garima@gmail.com"
    }
  }
];

Judoboy Alex
  • 326
  • 1
  • 14
  • 1
    Does this answer your question? [Highlight text using ReactJS](https://stackoverflow.com/questions/29652862/highlight-text-using-reactjs) – shanmukha vangaru Feb 05 '23 at 20:26

2 Answers2

2

The link that shanmukha vangaru suggested is a great place to start, but here is some working code to experiment with and study.

It uses the dangerouslySetInnerHTML prop but properly sanitises the input using DOMPurify, in order to be safe.

import { useState } from "react";
import DOMPurify from "dompurify";
const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "garima@gmail.com"
    }
  }
];

// Helper function to add highlighted markup to selected text
// based on the input keyword:
const highlighted = (keyword, text) =>
  // We sanitize the produced text to avoid XSS attacks
  // before passing the data to the dangerouslySetInnerHTML prop
  DOMPurify.sanitize(
    text.replace(
      new RegExp(`(${keyword})`, "gi"),
      "<span style='background:orange;'>$1</span>"
    )
);

export default function App() {
  const [keyword, setKeyword] = useState(null);
  // 1) Watch for input from the search box and update the state
  // The state change will trigger a re-render of the Component
  const handleOnChange = (e) => {
    setKeyword(e.target.value);
  };

  return (
    <>
      <input type="text" onChange={handleOnChange} />
      {posts.map((feed) => (
        <div key={feed.dateTimeCreated}>
          {feed.from.name} {feed.dateTimeLastModified}
          <p dangerouslySetInnerHTML={{ __html: highlighted(keyword, feed.fullText) }} />
        {/* The keyword is updated, there's a re-render and the feed text is filtered through the highlighter helper function to produce the highlighted markup */}
        </div>
      ))}
    </>
  );
}

Working demo:

const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "garima@gmail.com"
    }
  }
];

  const highlighted = (keyword, text) =>
    DOMPurify.sanitize(
      text.replace(
        new RegExp(`(${keyword})`, "gi"),
        "<span style='background:orange;'>$1</span>"
      )
    );

function App() {
  const [keyword, setKeyword] = React.useState(null);
  const handleOnChange = (e) => {
    setKeyword(e.target.value);
  };
  return (
    <React.Fragment>
      <input type="text" onChange={handleOnChange} />
      {posts.map((feed) => (
        <div key={feed.dateTimeCreated}>
          {feed.from.name} {feed.dateTimeLastModified}
          <p dangerouslySetInnerHTML={{ __html: highlighted(keyword, feed.fullText) }} />
        </div>
      ))}
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.3/purify.min.js" crossorigin></script>
<div id="root"></div>

As always, there are many ways to solve a problem in software development, so make sure to study the other proposed solutions in the link provided in the comments. Each solution, has always pros and cons and must be balanced according to the requirements and trade offs.

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • This does work, but just wondering about using `dangerouslySetInnerHTML` . I know it's considered bad to use due to security reasons. Why is it necessary to use it in this case? So `DOMPurify` is used to counter security issues that `dangerouslySetInnerHTML` bring, correct? – Judoboy Alex Feb 05 '23 at 21:13
  • 1
    If you are absolutely sure about the content passed to the dangerouslySetInnerHTML prop, e.g. this is your content, then you have nothing to worry about. If the content comes from user input, you should use DOMPurify or another sanitization library (e.g. Sanitize HTML, js-xss, etc.) to properly sanitize the content as there will always be possible from some malicious user to inject code into the content (XSS). – Kostas Minaidis Feb 05 '23 at 21:16
1

Can you check this solution

import React, { useState } from "react";

const App = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [text, setText] = useState("Lorem Ipsum is simply dummy text");

  const highlightText = (text, searchTerm) => {
    const regex = new RegExp(`(${searchTerm})`, "gi");
    const parts = text.split(regex);
    const highlighted = [];

    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      if (regex.test(part)) {
        highlighted.push(<mark key={i}>{part}</mark>);
      } else {
        highlighted.push(part);
      }
    }

    return highlighted;
  };

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p>{highlightText(text, searchTerm)}</p>
    </div>
  );
};

export default App;
Layeb Mazen
  • 142
  • 5
  • When input field is empty, every letter is highlighted for some reason. When I start to type then only typed letter is highlighted. So only issue is initial display. This can be another potential solution, just needs little more work. – Judoboy Alex Feb 05 '23 at 21:43