blueberryapps / react-load-script

React component that makes it easy to load 3rd party scripts

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Passing custom arguments to the script

julesterrien opened this issue · comments

Hey! What do you think of including the ability to pass custom props to the scripts that could be included either as attributes of the script tag, or as a data- attributes

For eg.

<Script
url="https://someUrl.com"
customProp="customPropValue"
onCreate={onCreate}
onError={onError}
onLoad={onLoad}
/>

At quick glance, the only edit necessary would be to change createScript to grab these props and add them to the script:

createScript() {
		const { onCreate, url, ...customProps } = this.props;
		const script = document.createElement('script');

		onCreate();

		if (customProps) {
                        // to include them as script attributes
			Object.keys(customProps).forEach((prop) => {
				script.setAttribute(prop, customProps[prop]);
			});
                       // or something like script.setAttribute(`data-${prop}`, customProps[prop]);
		}

		script.src = url;
		script.async = 1;

I'm working on an integration that would require attributes to be added directly to the script tag (not through data-), although this might be an isolated use case -- the standard seems to be to use data- to add custom data to a script tag (https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes)

@julesterrien Hi, thanks for the suggestion! Can you make a PR for that if you have time? I think that naming the prop attributes instead of customProps would work well

Cool can do. Do you think it should handle:

  • adding custom attributes to the script tag. ie. <script custom="value"/>.
  • adding custom as data-. ie. <script data-custom="value/>
  • both (either by adding props both as attributes and data- style attributes (ie. <script custom="value" data-custom="value"/>), or letting the dev define which option he/she prefers using another prop)

I think that all scenarios could be handled by attributes={{ 'data-custom': 'val', 'custom': 'hello' }} 👍

@julesterrien v0.0.5 published ✅