I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:
\'use strict\';
import \'../../styles/
My favorite way is to use React Helmet – it's a component that allows for easy manipulation of the document head in a way you're probably already used to.
e.g.
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<script src="https://use.typekit.net/foobar.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
</Helmet>
...
</div>
);
}
};
https://github.com/nfl/react-helmet
You can use npm postscribe to load script in react component
postscribe('#mydiv', '<script src="https://use.typekit.net/foobar.js"></script>')
Further to the answers above you can do this:
import React from 'react';
export default class Test extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.innerHTML = "document.write('This is output by document.write()!')";
this.instance.appendChild(s);
}
render() {
return <div ref={el => (this.instance = el)} />;
}
}
The div is bound to this
and the script is injected into it.
Demo can be found on codesandbox.io
If you need to have <script>
block in SSR (server-side rendering), an approach with componentDidMount
will not work.
You can use react-safe library instead. The code in React will be:
import Safe from "react-safe"
// in render
<Safe.script src="https://use.typekit.net/foobar.js"></Safe.script>
<Safe.script>{
`try{Typekit.load({ async: true });}catch(e){}`
}
</Safe.script>
for multiple scripts, use this
var loadScript = function(src) {
var tag = document.createElement('script');
tag.async = false;
tag.src = src;
document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')