Skip to content

Commit e1e356d

Browse files
committed
Set custom attributes + add test.
1 parent 35f41ca commit e1e356d

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/index.jsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ export default class Script extends React.Component {
88
onError: RPT.func.isRequired,
99
onLoad: RPT.func.isRequired,
1010
url: RPT.string.isRequired,
11+
attributes: RPT.object,
1112
};
1213

1314
static defaultProps = {
1415
onCreate: () => {},
1516
onError: () => {},
1617
onLoad: () => {},
18+
attributes: {},
1719
}
1820

1921
// A dictionary mapping script URLs to a dictionary mapping
@@ -76,11 +78,16 @@ export default class Script extends React.Component {
7678
}
7779

7880
createScript() {
79-
const { onCreate, url } = this.props;
81+
const { onCreate, url, attributes } = this.props;
8082
const script = document.createElement('script');
8183

8284
onCreate();
8385

86+
// add 'data-' or non standard attributes to the script tag
87+
if (attributes) {
88+
Object.keys(attributes).forEach(prop => script.setAttribute(prop, attributes[prop]));
89+
}
90+
8491
script.src = url;
8592
script.async = 1;
8693

src/index.test.jsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/* global document */
2+
13
import React from 'react';
24
import { shallow } from 'enzyme';
35
import Script from './index';
@@ -11,6 +13,11 @@ beforeEach(() => {
1113
onError: jest.fn(),
1214
onLoad: jest.fn(),
1315
url: 'dummy',
16+
attributes: {
17+
id: 'dummyId',
18+
dummy: 'non standard',
19+
'data-dummy': 'standard',
20+
},
1421
};
1522
wrapper = shallow(<Script {...props} />);
1623
});
@@ -75,3 +82,10 @@ test('componentWillUnmount should delete observers for the loader', () => {
7582
wrapper.instance().componentWillUnmount();
7683
expect(getObserver()).toBe(undefined);
7784
});
85+
86+
test('custom attributes should be set on the script tag', () => {
87+
const script = document.getElementById('dummyId');
88+
expect(script.getAttribute('id')).toBe('dummyId');
89+
expect(script.getAttribute('dummy')).toBe('non standard');
90+
expect(script.getAttribute('data-dummy')).toBe('standard');
91+
});

0 commit comments

Comments
 (0)