Insert HTML with React Variable Statements (JSX)

JavascriptHtmlReactjs

Javascript Problem Overview


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 = '<p>copy copy copy <strong>strong copy</strong></p>';

and to insert it into react like so, and have it work?

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

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.

Javascript Solutions


Solution 1 - Javascript

You can use dangerouslySetInnerHTML, e.g.

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

Solution 2 - Javascript

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.

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 - Javascript

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 - Javascript

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

const App = () => {
const span = <span> whatever your string </span>

const dynamicString = "Hehe";
const dynamicStringSpan = <span> {`${dynamicString}`} </span>

  return (
    <div>

      {span}

      {dynamicStringSpan}

    </div>
  );

};

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Solution 5 - Javascript

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.

Solution 6 - Javascript

To avoid linter errors, I use it like this:

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

Solution 7 - Javascript

You don't need any special library or "dangerous" attribute. You can just use React Refs to manipulate the DOM:

class MyComponent extends React.Component {
	
	constructor(props) {
		
		super(props);		
		this.divRef = React.createRef();
        this.myHTML = "<p>Hello World!</p>"
	}
	
	componentDidMount() {
		
		this.divRef.current.innerHTML = this.myHTML;
	}
	
	render() {
		
		return (
			
			<div ref={this.divRef}></div>
		);
	}
}

A working sample can be found here:

https://codepen.io/bemipefe/pen/mdEjaMK

Solution 8 - Javascript

Try Fragment, if you don't want any of above.

In your case, we can write

import React, {useState, Fragment} from 'react'

const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')

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

If you using hook want to set it in a state somewhere with any condition

const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);

Solution 9 - Javascript

If anyone else still lands here. With ES6 you can create your html variable like so:

render(){
    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>
    );
    return(
        <div>
            {thisIsMyCopy}
        </div>
    )
}

Solution 10 - Javascript

You can also include this HTML in ReactDOM like this:

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

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle HotchkissView Question on Stackoverflow
Solution 1 - JavascriptDouglasView Answer on Stackoverflow
Solution 2 - JavascriptYo WakitaView Answer on Stackoverflow
Solution 3 - Javascriptuser2903536View Answer on Stackoverflow
Solution 4 - Javascriptamitchauh4nView Answer on Stackoverflow
Solution 5 - JavascriptAmandeep Singh GhaiView Answer on Stackoverflow
Solution 6 - JavascriptTudor MorarView Answer on Stackoverflow
Solution 7 - JavascriptBemipefeView Answer on Stackoverflow
Solution 8 - JavascriptAdarsh PawarView Answer on Stackoverflow
Solution 9 - JavascriptHarryView Answer on Stackoverflow
Solution 10 - JavascriptGrassLandView Answer on Stackoverflow