Skip to content

Commit

Permalink
Modify withStyles HOC to hoist non-react statics (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderchr authored and koistya committed Aug 10, 2016
1 parent 6ff8064 commit f2a4d80
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 17 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
},
"dependencies": {
"babel-runtime": "^6.6.1",
"hoist-non-react-statics": "^1.0.5",
"loader-utils": "^0.2.14"
},
"devDependencies": {
Expand Down
39 changes: 22 additions & 17 deletions src/withStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,36 @@
*/

import React, { Component, PropTypes } from 'react';
import hoistStatics from 'hoist-non-react-statics';

function getDisplayName(ComposedComponent) {
return ComposedComponent.displayName || ComposedComponent.name || 'Component';
}

function withStyles(...styles) {
return (ComposedComponent) => class WithStyles extends Component {
static contextTypes = {
insertCss: PropTypes.func.isRequired,
};

static displayName = `WithStyles(${getDisplayName(ComposedComponent)})`;
static ComposedComponent = ComposedComponent;

componentWillMount() {
this.removeCss = this.context.insertCss.apply(undefined, styles);
return function wrapWithStyles(ComposedComponent) {
class WithStyles extends Component {
static contextTypes = {
insertCss: PropTypes.func.isRequired,
};

static displayName = `WithStyles(${getDisplayName(ComposedComponent)})`;
static ComposedComponent = ComposedComponent;

componentWillMount() {
this.removeCss = this.context.insertCss.apply(undefined, styles);
}

componentWillUnmount() {
setTimeout(this.removeCss, 0);
}

render() {
return <ComposedComponent {...this.props} />;
}
}

componentWillUnmount() {
setTimeout(this.removeCss, 0);
}

render() {
return <ComposedComponent {...this.props} />;
}
return hoistStatics(WithStyles, ComposedComponent);
};
}

Expand Down
24 changes: 24 additions & 0 deletions test/withStylesSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,28 @@ describe('withStyles(ComposedComponent, ...styles)', () => {
const decorated = withStyles('')(Container);
expect(decorated.ComposedComponent).to.equal(Container);
});

it('Hoists non-react statics of the composed component', () => {
class Foo extends Component {
render() {
return <div />;
}
}
Foo.someStaticProperty = true;

const decorated = withStyles('')(Foo);
expect(decorated.someStaticProperty).to.equal(true);
});

it('Does not hoist react statics of the composed component', () => {
class Foo extends Component {
render() {
return <div />;
}
}
Foo.propTypes = true;

const decorated = withStyles('')(Foo);
expect(decorated.propTypes).to.not.equal(true);
});
});

0 comments on commit f2a4d80

Please sign in to comment.