I have this component:
export class Demo extends React.Component<DemoProps, any> {
private foo: number;
constructor(props: DemoProps) {
super(props);
}
render() {
return (
<html>
<head>
<script>
// I would like to add an inline script here
</script>
</head>
<body>
<div id="root">
(hello world)
</div>
<div>
<progress id="hot-reload-progress-bar" value="100" max="100"></progress>
</div>
</body>
</html>
)
}
}
how can I add an inline script inside the <script></script> tags?
If try this:
getScript() {
const config = JSON.stringify({
env: process.env.NODE_ENV
});
return 'define(\"@config\", [], function () {' +
' return ' + config +';' +
'});'
}
<head>
<script>{this.getScript()} </script>
</head>
I get this on the front end:
<html><head><script data-main="/js/main" src="/vendor/require.js"></script><script>define("@config", [], function () { return {"env":"local"};}); </script></head><div><progress id="hot-reload-progress-bar" value="100" max="100"></progress></div><body><div id="root">Initial Home Page</div></body></html>
The browser cannot parse this because I get the: " characters instead of " or '
The best thing to do is probably use React's inborn facility - dangerouslySetInnerHTML - please see this link to the React docs:
https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml
Read the docs first! then look at my solution below.
The only way I got this feature working was with the following:
export class Demo extends React.Component<DemoProps, any> {
constructor(props: DemoProps) {
super(props);
}
getScript() { // return a string representing JS code
const config = JSON.stringify({
env: process.env.NODE_ENV
});
// return a plain JS object with the __html property
// set to the string
return {__html:'define("@config", [], function () {' +
' return ' + config +';' +
'});'}
}
render() {
return (
<html>
<head>
<script dangerouslySetInnerHTML={this.getScript()}/>
</head>
<body>
<div id="root">
</div>
</body>
</html>
)
}
}
Not sure if this would satisfy your needs, but you could put your script contents inside a component method and then call the method from within the jsx
export class Demo extends React.Component<DemoProps, any> {
private foo: number;
constructor(props: DemoProps) {
super(props);
}
scriptContents(){
//contents of the script in here
}
render() {
return (
<html>
<head>
<script>
{this.scriptContents()}
</script>
</head>
<body>
<div id="root">
(hello world)
</div>
<div>
<progress id="hot-reload-progress-bar" value="100" max="100"></progress>
</div>
</body>
</html>
)
}
}