简体   繁体   中英

className not working on dangerouslySetInnerHTML

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>

在此处输入图片说明

Complete component will look like this
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM