Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a react element using an html string? [duplicate]

var Klass = React.createClass({
  this.props.html_string = '<button>BUTTON_TEXT</button>';
  render: function(){
    return (
      <div className="wrapper">
        {this.props.html_string}
      </div>
    );
  }
});

Currently {this.props.html_string} gives me a text node. How can I make this a HTML DOM node?

like image 978
Derek Avatar asked Apr 17 '15 18:04

Derek


People also ask

How do you render a string as HTML in React?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

How do I add HTML code to React component?

Just use react-create-app template and the basic html (head, meta) things are already in place, Just modify the src dir to meet you needs. import React from 'react'; import './App. css'; // For Your CSS file class App extends React.

How do you repeat on React?

To repeat an element n times with React, we can use the Array function with the map array method. to create an array with 8 span elements with the same content by calling the Array with the n to create an empty array with n slots. Then we use the spread operator to make a copy of it.

Does React automatically escape HTML?

React applies auto-escaping As a result, React will automatically ensure that data that ends up in the page will not cause XSS attacks.


1 Answers

What you want is dangerouslySetInnerHTML

https://facebook.github.io/react/tips/dangerously-set-inner-html.html

function createMarkup() { return {__html: 'First &middot; Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />

Edit: you'll want to htmlencode the string.

like image 166
SnareHanger Avatar answered Sep 21 '22 15:09

SnareHanger