Skip to content

Hoc pattern, test fixes and clean-ups #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 35 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,35 @@

[![Build Status][travis.img]][travis.url] [![npm version][npm.img]][npm.url] [![npm downloads][npm.dl.img]][npm.dl.url] [![Dependencies][deps.img]][deps.url]

A React composition mixin for loading 3rd party scripts asynchronously. This component allows you to wrap component
that needs 3rd party resources, like reCAPTCHA or Google Maps, and have them load the script asynchronously.
A React HOC for loading 3rd party scripts asynchronously. This HOC allows you to wrap a component that needs 3rd party resources, like reCAPTCHA or Google Maps, and have them load the script asynchronously.

## Usage

The api is very simple `makeAsyncScriptLoader(Component, getScriptUrl, options)`. Where options can contain exposeFuncs, callbackName and globalName.
#### HOC api

- `Component`: The component to wrap.
- `getScriptUrl`: a string or function that returns the full URL of the script tag.
- options *(optional)*:
- `exposeFuncs`: Array of Strings. It'll create a function that will call the child component with the same name. It passes arguments and return value.
- `callbackName`: If the scripts calls a global function when loaded, provide the callback name here. It'll be autoregistered on the window.
- `globalName`: If wanted, provide the globalName of the loaded script. It'll be injected on the component with the same name *(ex: "grecaptcha")*
- `removeOnUnmount`: Boolean **default=false**: If set to true removes the script tag on the component unmount
`makeAsyncScriptLoader(getScriptUrl, options)(Component)`

- `Component`: The *Component* to wrap.
- `getScriptUrl`: *string* or *function* that returns the full URL of the script tag.
- `options` *(optional)*:
- `exposeFuncs`: *array of strings* : It'll create a function that will call the child component with the same name. It passes arguments and return value.
- `callbackName`: *string* : If the script needs to call a global function when finished loading *(for example: `recaptcha/api.js?onload=callbackName`)*. Please provide the callback name here and it will be autoregistered on `window` for you.
- `globalName`: *string* : If wanted, provide the globalName of the loaded script. It'll be injected on the component with the same name *(ex: "grecaptcha")*
- `removeOnUnmount`: *boolean* **default=false** : If set to `true` removes the script tag on the component unmount

#### HOC Component props
```
const AsyncScriptComponent = makeAsyncScriptLoader(URL)(Component);
---
<AsyncScriptComponent asyncScriptOnLoad={callAfterScriptLoads} />
```
- `asyncScriptOnLoad`: *function* : called after script loads


#### HOC Instance methods

- `getComponent()`: Using this method call you can retrieve the child component ref instance (the *Component* that is wrapped)

You can retrieve the child component using the function called `getComponent()`.

### Example

Expand All @@ -35,10 +48,10 @@ const callbackName = "onloadcallback";
const URL = `https://www.google.com/recaptcha/api.js?onload=${callbackName}&render=explicit`;
const globalName = "grecaptcha";

export default makeAsyncScriptLoader(ReCAPTCHA, URL, {
export default makeAsyncScriptLoader(URL, {
callbackName: callbackName,
globalName: globalName,
});
})(ReCAPTCHA);


// main.js
Expand Down Expand Up @@ -69,8 +82,7 @@ You can still retrieve the child component using `getComponent()`.
### Example

```js
const MockedComponent = React.createClass({
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh wow that was an old example X) Didn't realize I never update it to classes.

displayName: "MockedComponent",
class MockedComponent extends React.Component {

callsACallback(fn) {
fn();
Expand All @@ -79,37 +91,26 @@ const MockedComponent = React.createClass({
render() {
return <span/>;
}
});
};
MockedComponent.displayName = "MockedComponent";

let ComponentWrapper = makeAsyncScriptLoader(MockedComponent, "http://example.com", {
let ComponentWrapper = makeAsyncScriptLoader("http://example.com", {
exposeFuncs: ["callsACallback"]
});
let instance = ReactTestUtils.renderIntoDocument(
})(MockedComponent);

const instance = ReactTestUtils.renderIntoDocument(
<ComponentWrapper />
);

instance.callsACallback(function () { console.log("Called from child", this.constructor.displayName); });
```

## Notes

### History

With React 0.13, mixins are getting deprecated in favor of composition.

After reading this article, [Mixins Are Dead. Long Live Composition][dan_abramov],
I decided push react-script-loader a bit further and make a composition function that wraps component.

### Version to use

- __React < 15.5__: v0.8.0
- __React >= 15.5__: >= v0.9.0
Pre `1.0.0` and - `React < 15.5.*` support details in [0.11.1](https://github.com/dozoisch/react-async-script/tree/v0.11.1).

---

*Inspired by [react-script-loader][sl]*

*The build tools are highly inspired by [react-bootstrap][rb]*

[travis.img]: https://travis-ci.org/dozoisch/react-async-script.svg?branch=master
[travis.url]: https://travis-ci.org/dozoisch/react-async-script
[npm.img]: https://badge.fury.io/js/react-async-script.svg
Expand All @@ -118,7 +119,3 @@ I decided push react-script-loader a bit further and make a composition function
[npm.dl.url]: https://www.npmjs.com/package/react-async-script
[deps.img]: https://david-dm.org/dozoisch/react-async-script.svg
[deps.url]: https://david-dm.org/dozoisch/react-async-script

[dan_abramov]: https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
[sl]: https://github.com/yariv/ReactScriptLoader
[rb]: https://github.com/react-bootstrap/react-bootstrap/
61 changes: 31 additions & 30 deletions src/async-script-loader.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import React from "react";
import { Component, createElement } from "react";
import PropTypes from "prop-types";

let SCRIPT_MAP = {};

// A counter used to generate a unique id for each component that uses the function
let idCount = 0;

export default function makeAsyncScript(Component, getScriptURL, options) {
export default function makeAsyncScript(getScriptURL, options) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The below diff looks intense, but mostly just indentation due to HOC 😢

biggest changes are:

  • the added (props, context) to the constructor
  • added comments to steps inside of componentDidMount
  • passing the entry object to asyncScriptOnLoad

Copy link
Owner

@dozoisch dozoisch Aug 6, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can remove the whitespace from the diff => https://github.com/dozoisch/react-async-script/pull/34/files?w=1 . w=1 makes it easier to review in this case :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

^ that's awesome... i need to remember that for all time.. lol

options = options || {};
return function wrapWithAsyncScript(WrappedComponent) {
const wrappedComponentName =
Component.displayName || Component.name || "Component";
WrappedComponent.displayName || WrappedComponent.name || "Component";

class AsyncScriptLoader extends React.Component {
constructor() {
super();
class AsyncScriptLoader extends Component {
constructor(props, context) {
super(props, context)
this.state = {};
this.__scriptURL = "";
this.assignChildComponent = this.assignChildComponent.bind(this);
}

asyncScriptLoaderGetScriptLoaderID() {
Expand All @@ -31,12 +33,19 @@ export default function makeAsyncScript(Component, getScriptURL, options) {
return this.__scriptURL;
}

assignChildComponent(ref) {
this.__childComponent = ref;
}

getComponent() {
return this.__childComponent;
}

asyncScriptLoaderHandleLoad(state) {
this.setState(state, this.props.asyncScriptOnLoad);
// use reacts setState callback to fire props.asyncScriptOnLoad with new state/entry
this.setState(state,
() => this.props.asyncScriptOnLoad && this.props.asyncScriptOnLoad(this.state)
);
}

asyncScriptLoaderTriggerOnScriptLoaded() {
Expand All @@ -54,20 +63,30 @@ export default function makeAsyncScript(Component, getScriptURL, options) {
const scriptURL = this.setupScriptURL();
const key = this.asyncScriptLoaderGetScriptLoaderID();
const { globalName, callbackName } = options;

// check if global object already attached to window
if (globalName && typeof window[globalName] !== "undefined") {
SCRIPT_MAP[scriptURL] = { loaded: true, observers: {} };
}

// check if script loading already
if (SCRIPT_MAP[scriptURL]) {
let entry = SCRIPT_MAP[scriptURL];
// if loaded or errored then "finish"
if (entry && (entry.loaded || entry.errored)) {
this.asyncScriptLoaderHandleLoad(entry);
return;
}
// if still loading then callback to observer queue
entry.observers[key] = entry => this.asyncScriptLoaderHandleLoad(entry);
return;
}

/*
* hasn't started loading
* start the "magic"
* setup script to load and observers
*/
let observers = {};
observers[key] = entry => this.asyncScriptLoaderHandleLoad(entry);
SCRIPT_MAP[scriptURL] = {
Expand Down Expand Up @@ -122,19 +141,6 @@ export default function makeAsyncScript(Component, getScriptURL, options) {
}
};

// (old) MSIE browsers may call "onreadystatechange" instead of "onload"
script.onreadystatechange = () => {
if (this.readyState === "loaded") {
// wait for other events, then call onload if default onload hadn't been called
window.setTimeout(() => {
const mapEntry = SCRIPT_MAP[scriptURL];
if (mapEntry && mapEntry.loaded !== true) {
script.onload();
}
}, 0);
}
};

document.body.appendChild(script);
}

Expand Down Expand Up @@ -163,22 +169,16 @@ export default function makeAsyncScript(Component, getScriptURL, options) {

render() {
const globalName = options.globalName;
// remove asyncScriptOnLoad from childprops
let { asyncScriptOnLoad, ...childProps } = this.props;
// remove asyncScriptOnLoad from childProps
let { asyncScriptOnLoad, ...childProps } = this.props; // eslint-disable-line no-unused-vars
if (globalName && typeof window !== "undefined") {
childProps[globalName] =
typeof window[globalName] !== "undefined"
? window[globalName]
: undefined;
}
return (
<Component
ref={comp => {
this.__childComponent = comp;
}}
{...childProps}
/>
);
childProps.ref = this.assignChildComponent;
return createElement(WrappedComponent, childProps);
}
}
AsyncScriptLoader.displayName = `AsyncScriptLoader(${wrappedComponentName})`;
Expand All @@ -195,3 +195,4 @@ export default function makeAsyncScript(Component, getScriptURL, options) {
}
return AsyncScriptLoader;
}
}
Loading