Home > Net >  How to set color for some specific word
How to set color for some specific word

Time:09-22

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.

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

CodePudding user response:

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;
}

CodePudding user response:

Just replace the string, with the same string but with a style="color:(some color);"

defaultText.replace("software", "<span style='color:red;'>software</span>");

CodePudding user response:

import "./styles.css";

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

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

styles.css

.colorText{
   color red 

}

Try out with this solution. It worked for me

  • Related