Skip to content

Instantly share code, notes, and snippets.

@iMoses
Last active December 28, 2016 16:41
Show Gist options
  • Save iMoses/b5ba349f33d98b326d01043d07591176 to your computer and use it in GitHub Desktop.
Save iMoses/b5ba349f33d98b326d01043d07591176 to your computer and use it in GitHub Desktop.
// a simple implementation of a css modules decorator which utilizes the
// classNames package and automatically overrides the original className
import classNames from 'classnames/bind';
import React from 'react';
export default styles => Component => isStateless(Component)
? props => transformElement(Component(props), classNames.bind(styles))
: class extends Component { render() { return transformElement(super.render(), classNames.bind(styles)); } };
function transformElement(el, cx) {
let className = el && el.props.className;
if (className)
className = cx(typeof className === 'string' ? className.split(/\s+/g) : className);
return el && React.cloneElement(el, {...el.props, className}, recursiveTransform(el.props.children, cx));
}
function recursiveTransform(el, cx) {
if (React.isValidElement(el))
return transformElement(el, cx);
if (Array.isArray(el))
return React.Children.map(el, child => recursiveTransform(child, cx));
return el;
}
function isStateless(Component) {
return !('prototype' in Component && typeof Component.prototype.render === 'function');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment