1

If I have a template string with whitespace, say

(`${firstName},

Thanks for ordering ${product1}.

Your order has shipped.`);

How do I render that as html, including whitespace?

I have tried using innerHTML, but it results in

Hello Somebody, Thanks for ordering something. Your order has shipped.
<html>
<head>
    <meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8">

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>

<div id="test"></div>
  <script type="text/babel">

    var firstName = "Somebody"
    var product = "something"


    const element = (`
    Hello ${firstName},

    Thanks for ordering ${product}.

   Your order has shipped.
`);

document.getElementById('test').innerHTML = element;    

</script>
</body>
</html>```

Expected:

Hello Somebody, 

Thanks for ordering something. 

Your order has shipped.


Actual results:

Hello Somebody, Thanks for ordering something. Your order has shipped.
ezakto
  • 3,174
  • 22
  • 27
rgj
  • 21
  • 4
  • Possible duplicate of [How do I create a new line in Javascript?](https://stackoverflow.com/questions/5758161/how-do-i-create-a-new-line-in-javascript) – Murchiad Apr 11 '19 at 02:00

3 Answers3

1

HTML will collapse whitespace by default. You can either preserve whitespace using css white-space: pre or replace newline characters with <br> tags that will render the line breaks, like this:

document.getElementById('test').innerHTML = element.replace(/\n/g, '<br>')
ezakto
  • 3,174
  • 22
  • 27
0

You may try pre tag instead of div tag:

<pre id="test"></pre>
Even Lau
  • 1
  • 1
0

Since you use babel, why don't you write HTML inside const elements ?

const element = (
<div>
    <h3>Hello ${firstName}<h3>
    <p>Thanks for ordering ${product}</p>
    <p>Your order has shipped.</p>
</div>
);

FYI, You need wrap a div first

Alan Yong
  • 993
  • 2
  • 12
  • 25
  • I appreciate the suggestions, but I am not trying to find an alternative to what I described. I'm new to React, so I'm trying to understand why a book would teach things using only the console as an output for the code, when the idea is to learn how to get to single-page application coding. I am trying to use one of the examples originally output to the console to render on the screen. – rgj Apr 11 '19 at 13:47