Convert React.element to JSX String

I am trying to create a component that

  • Occupies children and
  • Gives children to the DOM as well
  • Shows DOM children in pre for documentation

One solution is to pass JSX as a separate prop . This makes it repeatable, since I can already access it through this.props.children . Ideally, I just need to somehow convert the children prop to string so that I can display it in pre to show that "this code produces this result."

This is what I still have

 class DocumentationSection extends React.Component{ render(){ return <div className="section"> <h1 className="section__title">{heading || ""}</h1> <div className="section__body"> {this.props.children}</div> <pre className="section__src"> //Change this to produce a JSX string from the elements {this.props.children} </pre> </div>; } } 

How can I get a jsx string in the format '<Div className='myDiv'>...</Div> when rendering DocumentationSection as

 <DocumentationSection heading='Heading 1'> <Div className='myDiv'>...</Div> </DocumentationSection> 

Thanks.

Edit :

I tried toString, it worked, gave [object Object]

+5
source share
2 answers

If you want an HTML representation of the React element, you can use #renderToString or renderToStaticMarkup .

 React.renderToString(<div>p</div>); React.renderToStaticMarkup(<div>p</div>); 

will create

 <div data-reactid=".1" data-react-checksum="-1666119235">p</div> 

and

 <div>p</div> 

respectively. However, you cannot display the parent as a string from the inside. If you need a parent, and then where you pass the parent pass from, run its renderToString version as the details for yourself.

+6
source

You can use react-element-to-jsx-string :

 import React from 'react'; import reactElementToJSXString from 'react-element-to-jsx-string'; console.log(reactElementToJSXString(<div a="1" b="2">Hello, world!</div>)); // <div // a="1" // b="2" // > // Hello, world! // </div> 
+3
source

Source: https://habr.com/ru/post/1237487/


All Articles