Skip to content

Instantly share code, notes, and snippets.

@jide
Last active September 4, 2015 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jide/ea29a612a767732b0c69 to your computer and use it in GitHub Desktop.
Save jide/ea29a612a767732b0c69 to your computer and use it in GitHub Desktop.
// 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