-
-
Save cameronhunter/331793a601315ced89ee51fcebd62f13 to your computer and use it in GitHub Desktop.
Converting a glamorous-like API to React styled components: https://astexplorer.net/#/gist/a206145e34e9ec363df8c6cd5bd9de75/latest
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
{ | |
"v": 2, | |
"parserID": "babylon7", | |
"toolID": "babelv7", | |
"settings": { | |
"babylon7": null | |
}, | |
"versions": { | |
"babylon7": "7.0.0", | |
"babelv7": "7.0.0" | |
} | |
} |
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 Header = widget( | |
{ | |
size: 30, | |
color: 'blue' | |
}, | |
({ text, color }) => ({ | |
text, color | |
}) | |
); |
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
export default function (babel) { | |
const { types: t } = babel; | |
return { | |
visitor: { | |
CallExpression(path) { | |
if (path.get('callee.name').node !== 'widget') { | |
return; | |
} | |
const calculateStyle = path.get('arguments.1'); | |
const staticStyle = path.get('arguments.0'); | |
const props = path.get('arguments.1.params.0.properties').map(p => p.node).map((n) => n.key.name); | |
path.replaceWithSourceString(` | |
(function createStyledComponent() { | |
const calculateStyle = ${calculateStyle}; | |
const staticStyle = ${staticStyle}; | |
const Component = function(props) { | |
return React.createElement( | |
'widget', | |
{ | |
staticStyle: staticStyle, | |
style: calculateStyle(props) | |
}, | |
props.children | |
); | |
}; | |
const areEqual = function(prevProps, nextProps) { | |
if (prevProps === nextProps) return true; | |
return ${props.map((name) => `prevProps.${name} === nextProps.${name}`).join('&&')} | |
} | |
return React.memo(Component, areEqual); | |
}()) | |
`); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment