Last active
November 27, 2020 06:19
-
-
Save gevgeny/126a10f53a30ed446c790f08e47736ac 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
const myStyled = (TargetComponent) => (strs, ...exprs) => class extends React.Component { | |
interpolateStyle() { | |
const style = exprs.reduce((result, expr, index) => { | |
const isFunc = typeof expr === 'function'; | |
const value = isFunc ? expr(this.props) : expr; | |
return result + value + strs[index + 1]; | |
}, strs[0]); | |
this.element.setAttribute('style', style); | |
} | |
componentDidMount() { | |
this.interpolateStyle(); | |
} | |
componentDidUpdate() { | |
this.interpolateStyle(); | |
} | |
render() { | |
return <TargetComponent {...this.props} ref={element => this.element = element } /> | |
} | |
}; | |
const primaryColor = 'coral'; | |
const Button = myStyled('button')` | |
background: ${({ primary }) => primary ? primaryColor : 'white'}; | |
color: ${({ primary }) => primary ? 'white' : primaryColor}; | |
padding: 0.25rem 1rem; | |
border: solid 2px ${primaryColor}; | |
border-radius: 3px; | |
margin: 0.5rem; | |
font-size: 1rem; | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment