derty14
derty14

Reputation: 115

Reactjs - how can i make line break in template strings and return for rendering?

You need to display the following content formatted on the screen:

divs:
 <div>my text</div> <div>my text</div> 

i tried to do this, but everything came out without line break:

 const HtmlCreator=()=>{
           let text="my text";
           return (`divs: \n <div>${text}</div> <div>${text}</div> `)
        {
    return (
    <div>
       <p><HtmlCreator/></p>
    </div>
)

Upvotes: 0

Views: 71

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Add whiteSpace:'pre' to your style :

<p style={{whiteSpace:'pre'}}><HtmlCreator /></p>

this is useful when you cannot modify the original data.

Upvotes: 1

George
George

Reputation: 36784

You can use <br />, but you'll need a wrapper. For that, you can use <React.Fragment>:

import React, { Fragment } from "react";

const HtmlCreator = () => {
  let text = "my text";

  return (
    <Fragment>
      divs
      <br />
      {`<div>${text}</div> <div>${text}</div>`}
    </Fragment>
  );
};

CodeSandbox Example

Your question implies you'd like to show the HTML itself (escape it) and not render it. If you meant the latter, you could do:

const HtmlCreator = () => {
  let text = "my text";

  return (
    <Fragment>
      divs
      <br />
      <div>{text}</div>
      <div>{text}</div>
    </Fragment>
  );
};

CodeSandbox Example

Upvotes: 1

Related Questions