Skip to content

Instantly share code, notes, and snippets.

@gevgeny
Last active November 27, 2020 06:19
Show Gist options
  • Save gevgeny/126a10f53a30ed446c790f08e47736ac to your computer and use it in GitHub Desktop.
Save gevgeny/126a10f53a30ed446c790f08e47736ac to your computer and use it in GitHub Desktop.
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