vuvu
vuvu

Reputation: 5338

How to print react-code inside code-tag?

I want to show my react code on a webpage, so visitors can read it. How can I convert my react code into a string and print it with indents?

react

   const reactcode= (
     <div>
       <div>
        <div>hello world</div>
       </div>
    </div>);

Upvotes: 0

Views: 1856

Answers (1)

Aron
Aron

Reputation: 9248

Method 1: Separate newline-delineated strings:

const reactcode = '<div>' +
'\n  <div>' + 
'\n    <div>hello world</div>' + 
'\n  </div>' + 
'\n</div>)';

Method 2: ES2015 template literals and much simpler

const reactcode = `
<div>
   <div>
     <div>hello world</div>
   </div>
</div>`;

Note the backticks (`) at the start and end of the string.

The reason method 2 works is because template literals can span multiple lines.

EDIT:

I just realised that what you're looking for is a way to convert actual React code to a string, not just print a string. It looks like the npm jsx-to-string module could help with this.

Upvotes: 1

Related Questions