Harshan
Harshan

Reputation: 37

how to highlight multiple text with multiple colors with in react JS

I want to make multiple texts with multiple colors like red, green, yellow something like that now it is working for only one color I need each text in a different color please help me here is the code https://codesandbox.io/s/quizzical-fire-qhu3hd?file=/src/App.js

import React from "react";

function App() {
  const highlightText = (text, textToMatch) => {
    const matchRegex = RegExp(textToMatch.join("|"), "ig");
    const matches = [...text.matchAll(matchRegex)];
    console.log(matches);
    return text.split(matchRegex).map((nonBoldText, index, arr) => (
      <div key={index}>
        {nonBoldText}
        {index + 1 !== arr.length && <mark>{matches[index]}</mark>}
      </div>
    ));
  };
  return (
    <h4>
      {highlightText(
        "The aim of this study was to someting  in vitro the potential of Aloe Vera juice as a skin permeation enhancer; worong text is added here to which Aloe Vera itself permeates the skin. Saturated solutions of caffeine, colchicine, mefenamic acid, oxybutynin, and quinine were prepared at 32 degrees C in Aloe Vera juice and water (control) and used to dose porcine ear skin",
        ["Aloe Vera", "and", "study"]
      )}
    </h4>
  );
}

export default App;

Upvotes: 1

Views: 812

Answers (2)

Tejashree Surve
Tejashree Surve

Reputation: 121

You need the array of colour. Please try this

     const highlightText = (text, textToMatch) => {
        const matchRegex = RegExp(textToMatch.join("|"), "ig");
        const matches = [...text.matchAll(matchRegex)];
// this consist of the color array 
        const color = ["green", "red", "yellow"];
        return text.split(matchRegex).map((nonBoldText, index, arr) => (
          <div key={index}>
            {nonBoldText}
            {index + 1 !== arr.length && (
              <mark
                style={{
// and this match the color index and textMatchIndex
                  backgroundColor:
                    color[
                      matches[index] ? textToMatch.indexOf(matches[index][0]) : ""
                    ]
                }}
              >
                {matches[index]}
              </mark>
            )}
          </div>
        ));
      };

enter image description here

Upvotes: 1

Kairav Thakar
Kairav Thakar

Reputation: 1001

Can you please check below link, It have different class name based on this

I need dynamic all this array values comes to from on handelChaneg from the input box i need fist word into red, the second word into green third into green ["Aloe Vera", "and", "study"]

: https://codesandbox.io/s/charming-dirac-m3w8z2?file=/src/App.js

You will find different class name and then you can define the css based on the colour class name.

Please let me know if you have any question

Upvotes: 0

Related Questions