skip to Main Content

After sending a to an API with a ‘search value’ that searches the database for the value and respond with data containing the value. I want to highlight the given word or search value in the response. The respond is populated to the UI

<center>
    {Object.keys(Disp).map((key, i) => (
      <center key={i} className="PublicationCard">
        <span> {key}</span>
        <a href={"https://www." + Disp[key]}> View Publication</a>
      </center>
    ))}
  </center>

The Key is a sentence but I want to bolden a word in the key
For example, let say the key is "Discussions about Supervised Artificial Intelligence" and the search query was artificial intelligence, all I want to do is to bold the search query that is "artificial intelligence’ in the UI

2

Answers


  1. Maybe you can create a function to generate multiple span tags.

    function GenerateSpan({ text, search }) {
        const reg = new RegExp(`(.*)(${search})(.*)`, "g")
        const array = [...text.matchAll(reg)]
        if (array.length > 0) {
            return array[0].slice(1).map((textPart, index) => {
                return <span key={index} className={textPart === search ? "highlight" : ""}>{textPart}</span>
            })
        } else {
            return <span>{text}</span>
        }
    }
    

    And use in your code :

    <GenerateSpan text=key search="Supervised"/>
    

    And then add style for class "highlight

    .highlight{
    font-weight: bold
    }
    

    So Finally :

    <center>
        {Object.keys(Disp).map((key, i) => (
          <center key={i} className="PublicationCard">
            <GenerateSpan text=key  search="Supervised"/>
            <a href={"https://www." + Disp[key]}> View Publication</a>
          </center>
        ))}
      </center>
    
    Login or Signup to reply.
  2. The example with RegExp works faster, but here is a simpler way.

    function Highlighter({ highlight = '', children: text }) {
      const index = text.toLowerCase().indexOf(highlight.toLowerCase());
    
      if (index >= 0 && highlight.length) {
        const beforeHighlight = text.substring(0, index);
        const highlightedPart = text.substring(index, index + highlight.length);
        const afterHighlight = text.substring(index + highlight.length);
    
        return (
          <highlight-text>
            {beforeHighlight}
            <span>{highlightedPart}</span>
            {afterHighlight}
          </highlight-text>
        );
      }
    
      return <>{text}</>;
    }
    
    export default Highlighter;
    

    And use it like:

    <Highlighter highlight={'Recursion'}>
      {'Recursion a misunderstood topic'}
    </Highlighter>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search