Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render an html entity in React.js without JSX

ReactDOM.render(
  React.createElement(
    "button",
    {"type": "button", "className": "close"},
    "×"),
  document.getElementById('container')
);

Prints '& times;' instead of ×

I was able to fix it by using dangerouslySetInnerHTML, but as the name states, I don't think dangerously is the best possible solution

ReactDOM.render(
  React.createElement(
    "button",
    {"type": "button", "className": "close", "dangerouslySetInnerHTML" : {__html: "×"}},
    null),
  document.getElementById('container')
);

You can find the last snippet here:

https://jsfiddle.net/pzb3ygxj/

like image 857
Onilton Maciel Avatar asked Jun 10 '16 17:06

Onilton Maciel


People also ask

Is it possible to use React without JSX?

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.

How do I render HTML data in react JS?

React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM.render() .

Can you use JSX without Babel?

React doesn't require babel but the library is built on the concept of using ES6 javascript syntax. React app however can be built with old ES5 syntax and JSX which would remove the need for Babel but you would lose the potential benefits of ES6.

How render HTML tag in string 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).


1 Answers

You could use an escaped unicode code point:

ReactDOM.render(
  React.createElement(
    "button",
    {"type": "button", "className": "close"},
    "\u00D7"),
  document.getElementById('container')
);

You can even just use the literal character:

ReactDOM.render(
  React.createElement(
    "button",
    {"type": "button", "className": "close"},
    "×"),
  document.getElementById('container')
);

The HTML entity, in a string, is escaped by React.

There's some documentation here:

https://facebook.github.io/react/docs/jsx-in-depth.html#string-literals

like image 64
Bo Borgerson Avatar answered Sep 28 '22 03:09

Bo Borgerson