Skip to content

Instantly share code, notes, and snippets.

@lumie1337
Created September 13, 2018 17:32
Show Gist options
  • Save lumie1337/3311cb7c69f7e6bdd8e9343efe2d40a0 to your computer and use it in GitHub Desktop.
Save lumie1337/3311cb7c69f7e6bdd8e9343efe2d40a0 to your computer and use it in GitHub Desktop.
import React from 'react';
import ReactDOM from 'react-dom';
function WrapperStyle(props) {
return (
<div style={{padding: "10px", border: "10px solid red"}}>
{props.children}
</div>
)
}
function WrapperStyleOnce(Component) {
const A = function (props) {
let isAlreadyWrapped = false;
React.Children.forEach(props.children, child => {
if(child.type && child.type.displayName == "WrapperStyle")
isAlreadyWrapped = true;
})
if(isAlreadyWrapped) {
return (
<React.Fragment>
{props.children}
</React.Fragment>
)
} else {
return (
<WrapperStyle>{props.children}</WrapperStyle>
)
}
}
A.displayName = "WrapperStyle"
return A
}
// Components that use it
function Component1_raw(props) {
return (
<React.Fragment>
{props.children}
</React.Fragment>
)
}
function Component2_raw(props) {
return (
<React.Fragment>
{props.children}
</React.Fragment>
)
}
const Component1 = WrapperStyleOnce(Component1_raw)
const Component2 = WrapperStyleOnce(Component2_raw)
// Example use
function App(props) {
return (
<Component1>
<Component2>
Example
</Component2>
</Component1>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment