Skip to content

Commit cb6a193

Browse files
committed
injectInComponent only first time
1 parent b2a7631 commit cb6a193

File tree

2 files changed

+60
-18
lines changed

2 files changed

+60
-18
lines changed

src/injector.js

+22-18
Original file line numberDiff line numberDiff line change
@@ -25,26 +25,30 @@ function injectInElement(component, componentName) {
2525
}
2626

2727
function injectInComponent(Component, componentName) {
28-
const componentPrototype = Component.prototype;
29-
const componentConstructor = Component;
28+
let newComponent = Component;
29+
if (!Component.hasReactCSSOM) {
30+
const componentPrototype = Component.prototype;
31+
const componentConstructor = Component;
3032

31-
//eslint-disable-next-line
32-
const newComponent = function ReactComponent(...params) {
33-
componentConstructor.apply(this, [...params]);
34-
const originalRender = this.render;
35-
this.render = () => (
36-
injectInElement(
37-
originalRender.apply(this),
38-
componentName || this.constructor.displayName || this.constructor.name
39-
)
40-
);
41-
};
33+
//eslint-disable-next-line
34+
newComponent = function ReactComponent(...params) {
35+
componentConstructor.apply(this, [...params]);
36+
const originalRender = this.render;
37+
this.render = () => (
38+
injectInElement(
39+
originalRender.apply(this),
40+
componentName || this.constructor.displayName || this.constructor.name
41+
)
42+
);
43+
};
4244

43-
//eslint-disable-next-line
44-
newComponent.prototype = componentPrototype;
45-
Object.keys(Component).forEach((x) => {
46-
newComponent[x] = Component[x];
47-
});
45+
newComponent.prototype = componentPrototype;
46+
Object.keys(Component).forEach((x) => {
47+
newComponent[x] = Component[x];
48+
});
49+
50+
newComponent.hasReactCSSOM = true;
51+
}
4852

4953
return newComponent;
5054
}

test/injector.js

+38
Original file line numberDiff line numberDiff line change
@@ -258,5 +258,43 @@ describe('injector', () => {
258258
className: '⚛Foo ',
259259
});
260260
});
261+
262+
it('should inject only the first time', () => {
263+
//eslint-disable-next-line
264+
class Foo extends React.Component {
265+
render() {
266+
return (
267+
<div />
268+
);
269+
}
270+
}
271+
272+
let oldClass = Foo;
273+
let Bar = inject(Foo)();
274+
expect(oldClass).toNotEqual(Bar);
275+
expect(Foo.hasReactCSSOM).toBeFalsy();
276+
expect(Bar.hasReactCSSOM).toBeTruthy();
277+
oldClass = Bar;
278+
Bar = inject(Foo)();
279+
expect(oldClass).toEqual(Bar);
280+
281+
oldClass = React.Component;
282+
React.Component = inject(React.Component)();
283+
expect(oldClass).toNotEqual(React.Component);
284+
oldClass = React.Component;
285+
React.Component = inject(React.Component)();
286+
expect(oldClass).toEqual(React.Component);
287+
288+
//eslint-disable-next-line
289+
class Baz extends React.Component {
290+
render() {
291+
return (
292+
<div />
293+
);
294+
}
295+
}
296+
297+
expect(Baz.hasReactCSSOM).toBeTruthy();
298+
});
261299
});
262300
});

0 commit comments

Comments
 (0)