3

I'm passing some text to a component:

<Component 
 text={`text with <span style={{fontWeight:bold}}>${thisPart}</span> emphasized`}
/>

Although it certainly can't work but I guess it shows my intentions well. Any idea how to make it work?

2 Answers 2

4

Do not use dangerouslySetInnerHTML for this. That is an anti-pattern.

<MyComponent>
 <span>text with</span>
 <strong>{thisPart}</strong>
 <span>emphasized</span>
</MyComponent>

The 2 span and 1 strong elements are accessible via the MyComponent children property

class MyComponent extends React.Component {
  render () {
    return (
      <div>
        <p>some text</p>
        <p>{this.props.children}</p>
      </div>
    )
  }
}

Would render

<div>
  <p>some text</p>
  <p>
    <span>text with</span>
    <strong>this part</strong>
    <span>emphasized</span>
  </p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

3

You cannot pass stringified HTML to a component because it opens XSS vulnerabilities.

If you must render html then you are required to use dangerouslySetInnerHTML

source:

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

3 Comments

Ah I see thanks for the quick answer. Seems I should avoid using this, any idea how to simply make part of my text bold?
If the text does not come from user input, for example if it's hard coded, it's fine to use dangerouslySetInnerHTML
@StanleyLuo here's a react component that does that for you github.com/bvaughn/react-highlight-words#usage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.