4

Let's say I have a simple template string :

const foo = `<div>foo</div>`;

How do I go about rendering this template string as HTML ? It renders it as plain text if I do the following :

return({ foo });

Output:

<div>foo</div>

Expected output:

foo
Chuck
  • 351
  • 1
  • 6
  • 20

4 Answers4

6

I think what you try to do is

const foo = `<div>foo</div>`;
<div dangerouslySetInnerHTML={{ __html: foo }}></div>

Related question.

React documentation.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
  • or you could also give the div an id and do this in the code behind – mast3rd3mon Mar 21 '18 at 16:02
  • That works, thanks. I wonder why it is so complicated to render it as HTML. Isn't this one of the main feature of string template in ES6 ? – Chuck Mar 21 '18 at 16:06
  • 1
    @Chuck no no no :) template literals have nothing to do with HTML, they are just language feature. React team decided that this kind of injecting HTML is unsafe and that's why you need to explicitly use `dangerouslySetInnerHTML`. – Tomasz Mularczyk Mar 21 '18 at 16:11
  • 2
    @mast3rd3mon While this is a generaly valid html case, adding id for such purpose is a bad practice in React. You could add a ref, and insert this inside ComponentDidMount by hooking to the ref element or use dangerouslySetInnerHTML which is the preferred method. – Vlatko Vlahek Mar 21 '18 at 16:59
  • @VlatkoVlahek ah, my bad, i wasnt aware of there being major differences, thanks for clearing that up – mast3rd3mon Mar 21 '18 at 16:59
1

You note reactjs as a tag here. Instead of specifying the html as a string, make foo a functional react component.

To do that, make sure you have import React as 'react';.
Then, set foo as the functional component, i.e.:

const foo = () => <div>foo</div>;

Then, you can use that wherever you please. React components are just functions (or classes) that return jsx.

Your question is fairly open-ended, so you may be looking for some of the above answers, but this is one approach.

  • Thanks for this. I ended up using the dangerouslySetInnerHTML for a bit, but quickly opted for another solution so I didn't need such code. Your answer is probably the better one, as it seems clean 'React' wise. – Chuck Mar 22 '18 at 08:37
0

Off the top of my head there's 2 ways to parse a string (doesn't have to be a tl) into HTML: .innerHTML property and the more powerful .insertAdjacentHTML() method.

Demo

var tl = `
  <video src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' controls width='320'></video>`;
  
document.body.innerHTML = tl;

document.body.insertAdjacentHTML('afterbegin', tl);
   
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

if you want to show the string of html as html page its better to do this:

<text>{{ info | safe }}</text>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
mahi
  • 1