I am trying to build a component which,
pre
for documentation sakeOne solution is to pass the JSX as a separate prop
as well. This makes it repetitive since I am already able to access it through this.props.children
. Ideally, I just need to somehow convert the children
prop as a string
so that I can render it in a pre
to show that "this code produces this result".
This is what I have so far
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 the a jsx string in the format '<Div className='myDiv'>...</Div>
when I render DocumentationSection as
<DocumentationSection heading='Heading 1'> <Div className='myDiv'>...</Div> </DocumentationSection>
Thanks.
Edit:
I tried toString, it dint work, gave [object Object]
There're several ways to convert HTML Strings to JSX with React. One way is to put the string in between curly braces in our component. Another way is to put the string in an array with other strings or JSX code. Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.
A ReactElement type could be considered the primitive definition for other types, such as a JSX. Element or JSX. IntrinsicElements . A ReactNode type can be a ReactElement , a string , a number , or even null , among other types.
You can use https://magic.reactjs.net/htmltojsx.htm which is an online HTML to JSX compiler. Show activity on this post. You can also use https://transform.tools/html-to-jsx beside https://magic.reactjs.net/htmltojsx.htm as mentioned above.
You can nest JSX elements inside of other JSX elements, just like in HTML.
If you want the HTML representation of a React element you can use #renderToString
or #renderToStaticMarkup
.
ReactDomServer.renderToString(<div>p</div>); ReactDomServer.renderToStaticMarkup(<div>p</div>);
will produce
<div data-reactid=".1" data-react-checksum="-1666119235">p</div>
and
<div>p</div>
respectively. You will however not be able to render the parent as a string from within itself. If you need the parent too then from where you render the parent pass a renderToString
version of it as props to itself.
React.renderToString
is depreciated as of React v0.14.0
, it's recommended to use ReactDOMServer.renderToString
instead.
e.g
import ReactDOMServer from 'react-dom/server' ... ReactDOMServer.renderToString(YourJSXElement())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With