Home  >  Q&A  >  body text

How to convert it to html element?

I'm trying to create a function that highlights words in a sentence. Here is the corresponding code.

highlightText = () => {
        const {
            questionItem,
        } = this.props;
        const words = questionItem.split(/\s+/);
        const highlighted = words.map((word, index) => (
            <span key={index} className="highlighted-word">{word}</span>
        ));
        const text = highlighted.join(' ');
        console.log(text);
        console.log({ highlighted });
        return highlighted;
    }

Here, if I console "text", I get [Object object], so I return "highlight" and then use reduce to join it.

const text3 = <p>{this.highlightText().reduce((prev, curr) => [prev, ' ', curr])}</p>;

I want to use this "text3" in the component. The problem is that I get "text3" as

I want it to be an HTML element so I can use it in my component. How can I convert it? Also, if I display

{this.highlightText().reduce((prev, curr) => [prev, ' ', curr])}

directly in the web page instead of Using it in my component works fine.

P粉248602298P粉248602298431 days ago618

reply all(1)I'll reply

  • P粉211600174

    P粉2116001742023-09-09 13:00:55

    Just create a new component with props. Try this...

    export default function HighlightText({text}) {
     return <span className="Add_HighlightText_Class" >{text}</span>

    reply
    0
  • Cancelreply