Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render (print) JSX as String?

Here JSX is scode sample:

export default class Element extends React.Component {   render() {     return (       <div>         <div className="alert alert-success">           {this.props.langs.map((lang, i) => <span key={i} className="label label-default">{lang}</span>)}         </div>       </div>     )   } } 

How to get string like this?

<div><div className="alert alert-success">{this.props.langs.map((lang, i) => <span key={i} className="label label-default">{lang}</span>)}</div></div> 

UPD: I got React components which I render on the server. I want to get them as a strings to transform them for another templating library on client side.

like image 282
user1704398 Avatar asked Apr 14 '17 18:04

user1704398


People also ask

Is JSX a string?

This funny tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

How do I render a string in HTML?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

How do you display text in React JS?

If you want to display it in an alert window, you need to call a function to trigger the window. However, if you need to show the message in your render, you can use a state to manage that. If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.


1 Answers

just call renderToStaticMarkup() and you should get the static html markup language generated by React.

somewhat like this:

import ReactDOMServer from 'react-dom/server'; import Element from './path/to/element/class';  const element = <Element />;  ReactDOMServer.renderToStaticMarkup(element) 

here are some more docs about this:

https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup

like image 134
beniutek Avatar answered Sep 19 '22 19:09

beniutek