Applying span to a string in a reaction returns [object Object] instead of giving me stretched text

I am trying to apply span in some words in a sentence.

return "hello how are you hello".replace(/hello|you/gi, <span className="some-class">"new"</span>);

In my opinion, I see [Object] instead of (span) new (span) as (span) new (span) (span) new (span)

I also tried using the dangerous SetInnerHTML, but no luck. I still get [object Object]

+4
source share
1 answer

String.prototype.replacereturns a string, so it converts the call React.createElementto a string [object Object].

Instead, you may need to break the sentence into words, put a card on them and return jsx if it matches your regular expression, otherwise it will return a string.

var stringArray = "hello how are you hello".split(" ")
var regex = /hello|you/i
var elements = stringArray.map(string =>
  regex.test(string) ? <span>{ string }</span> : string
)

render() {
  return <div>{ elements }</div>
}
0

Source: https://habr.com/ru/post/1629230/


All Articles