Insert HTML with React Variable Statements (JSX)

Insert HTML with React Variable Statements (JSX)

I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:
var thisIsMyCopy = ‘

copy copy copy strong copy

‘;

and to insert it into react like so, and have it work?
render: function() {
return (

{thisIsMyCopy}

);
}

and have it insert the HTML as expected? I haven’t seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work.

Solutions/Answers:

Solution 1:

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

Solution 2:

Note that dangerouslySetInnerHTML can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.

It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.

Related:  What is data serialization ?

Example:

import DOMPurify from 'dompurify'

const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
    );
}

Solution 3:

dangerouslySetInnerHTML has many disadvantage because it set inside the tag.

I suggest you to use some react wrapper like i found one here on npm for this purpose.
html-react-parser does the same job.

import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content">{Parser(thisIsMyCopy)}</div>
    );
}

Very Simple 🙂

Solution 4:

By using '' you are making it to string. Use without inverted commas it will work fine.

Solution 5:

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

Solution 6:

import { Fragment } from 'react' // react version > 16.0

var thisIsMyCopy = (
  <Fragment>
    <p>copy copy copy&nbsp;
    <strong>strong copy</strong>
    </p>
  </Fragment>
)

By using ” the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element –

  1. Remove the '' and it would work
  2. Use <Fragment> to return a HTML element.
Related:  Javascript: how to validate dates in format MM-DD-YYYY?