I’ve come up against a common problem when writing React components that depend on a 3rd party JS and CSS files.
Do I load these 3rd party files every time, and pay the performance cost, or manually hack a way to load them when my component is first used?
I decided to fix this properly, which has resulted in a simple React component I’ve open sourced called ReactDependentScript. You simply wrap your components in <ReactDependentScript …. >, telling it what JS and CSS files to load, and it loads them first, and only when they successfully load does it render the child components.
It also supports taking a function prop to call to render the child components lazily.
For example, you can load jQuery, and then render jQuery plugins or simply use the $ function.
You can do more interesting things like load the Stripe JS code for their Checkout flow.
Have a play with it at https://github.com/shaneosullivan/ReactDependentScript, or install it from NPM (https://www.npmjs.com/package/react-dependent-script) with
yarn add react-dependent-script
It’s MIT licensed so use it as you wish. Please feel free to provide feedback or changes through Github.