Last active
December 28, 2016 16:41
-
-
Save iMoses/b5ba349f33d98b326d01043d07591176 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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