Last active
September 4, 2015 16:20
-
-
Save jide/ea29a612a767732b0c69 to your computer and use it in GitHub Desktop.
This file contains 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
// customPropToClassName.js | |
const traverse = element => { | |
if (element.props) { | |
let props = {}; | |
if (element.props.customProp) { | |
// Inject className or anything you want | |
props.className = 'important-class'; | |
} | |
if (element.props.children) { | |
props.children = Array.isArray(element.props.children) ? | |
element.props.children.map(child => traverse(child)) : | |
traverse(element.props.children); | |
} | |
return React.cloneElement(element, props); | |
} | |
else { | |
return element; | |
} | |
}; | |
// Secret sauce: We extend the decorated component and override its render method. | |
export default WrappedComponent => class extends WrappedComponent { | |
render(...args) { | |
return traverse(super.render(...args)); | |
} | |
}; | |
//------------------------- | |
// App.js | |
import customPropToClassName from './customPropToClassName'; | |
@customPropToClassName | |
export default class Example extends React.Component { | |
render() { | |
return ( | |
<div customProp='something' id='wrapper'> | |
<p customProp='another'/> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment