[javascript] 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 = '<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.

This question is related to javascript html frontend reactjs react-jsx

The answer is


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 :)


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>
    );
}

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.

To avoid linter errors, I use it like this:

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

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>
    )
}

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


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.


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


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>);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to frontend

What is {this.props.children} and when you should use it? Vue.js—Difference between v-model and v-bind nodemon command is not recognized in terminal for node js server How to get all the values of input array element jquery Insert HTML with React Variable Statements (JSX) Get form data in ReactJS What is Bootstrap? What are the most common font-sizes for H1-H6 tags Convert javascript array to string good postgresql client for windows?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-jsx

Best practice when adding whitespace in JSX Render Content Dynamically from an array map function in React Native Warning: Failed propType: Invalid prop `component` supplied to `Route` How to pass props to {this.props.children} Expected corresponding JSX closing tag for input Reactjs Why calling react setState method doesn't mutate the state immediately? Can you force a React component to rerender without calling setState? React / JSX Dynamic Component Name How to loop and render elements in React.js without an array of objects to map? ReactJS: "Uncaught SyntaxError: Unexpected token <"