Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set color for some specific word

I have the following code.

    export default function App() {
      const defaultText = "Your partner for software innovations";
      const colorText = "softWare";

      const result = defaultText.split(" ").map((txt) => txt);
      return <div className="App">{result}</div>;
    }

defaultText is my data from the backend.

colorText is a word that should be colored.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I am trying to do the following. I want to map through the defaultText and compare if txt === colorText then set that word for example in red color.

I easily can map defaultText as you see but I can’t understand how to implement that filtering logic.

The final result should be like this

>Solution :

You can split the text into parts and then add a class to the text to highlight.

Pseudo code:

const defaultText = "Your partner for software innovations";
const colorText = "software";

const segments = defaultText.split(colorText);

return (
  <div className="App">
    {segments.map((segment, index) => (
      <Fragment key={index}>
        <span>{segment}</span>
        {(index !== segments.length - 1) && (<span>{colorText}</span>)}
      </Fragment>
    )}
  </div>
);

And CSS:

span.highlight {
  color: red;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading