I've initial string
like this:-
My first name is @John# and last name is %Smith#.
Where I'll replace:-
@
with <span className="contentDescHighlighted">
%
with <span className="contentDescHighlighted content_bold">
#
with </span>
the working code is as follow:-
const handleAddingHighlight = (data) => {
let changeAT = data.replaceAll(`@`, `<span className="contentDescHighlighted">`)
let changePercentage = changeAT.replaceAll(`%`, `<span className="contentDescHighlighted content_bold">`)
let highlightedData = changePercentage.replaceAll(`#`, `</span>`); console.log(highlightedData)
return highlightedData
}
After changing the string
, then I'll inject them using dangerouslySetInnerHTML
as follow:-
<p
className="contentDesc"
dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
></p>
Unfortunately, the styling/className applied didn't take any effect at all as shown below:-
// what it should looks like
<p className="contentDesc">
My first name is <span className="contentDescHighlighted">John</span> and last name is <span className="contentDescHighlighted content_bold">Smith</span>.
</p>
// current outcome when using dangerouslySetInnerHTML
<p
className="contentDesc"
dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
></p>
export default function Test() {
const handleAddingHighlight = (data) => {
let changeAT = data.replaceAll(`@`, `<span className="contentDescHighlighted">`)
let changePercentage = changeAT.replaceAll(`%`, `<span className="contentDescHighlighted content_bold">`)
let highlightedData = changePercentage.replaceAll(`#`, `</span>`); console.log(highlightedData)
return highlightedData
}
return (
<>
{/* what it should looks like */}
<p className="contentDesc">
My first name is <span className="contentDescHighlighted">John</span> and last name is <span className="contentDescHighlighted content_bold">Smith</span>.
</p>
{/* current outcome when using dangerouslySetInnerHTML */}
<p
className="contentDesc"
dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
></p>
</>
)
}
This is the issue. content rendered using dangerouslySetInnerHTML
property must be HTML
elements. They aren't JSX
at all.
It should be
class
(which is HTML attribute)
instead of
className
(which is JSX attribute)