sometime, i want ignore trans-pile in renderToString.
i'm using React as template engine to generate base of template (html, header, body). i need to inject a value (a json object as string,converted with JSON.stringify) to can access to it as global variable on the browser.
this is my Template component:
export default function (props) {
return (
<html>
<head>
<meta charSet="utf-8"/>
</head>
<body className="rtl">
<div id="app-root"></div>
<script>
myValue = {JSON.stringify(props.obj)}
</script>
</body>
</html>
);
}
this is render and pass value place:
let template = <Template obj={obj}/>;
template = ReactDOMServer.renderToString(template);
template = '<!DOCTYPE html>' + template;
res.status(status).send(template);
after running this, 'myValue' is undefined because renderToString insert insert as HTML comment and also change structure of data (convert characters) like this:
<script>
myValue = <!-- -->{"a":"a","b":"b"}
</script>
how to fix it?
Try this https://zhenyong.github.io/react/tips/dangerously-set-inner-html.html. Like this:
<script dangerouslySetInnerHTML={JSON.stringify(props.obj)} />