Last active
October 14, 2019 01:49
-
-
Save EnixCoda/9c480a73415fd8b37e4a7b101a7443b9 to your computer and use it in GitHub Desktop.
simple styled-components
This file contains hidden or 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
/* | |
* Usages | |
* | |
* native tags | |
* styled.div`color: red;` | |
* | |
* custom components | |
* styled((props) => <div {...props} />)`color: red;` | |
* | |
*/ | |
const generateStylesheet = (strings, bubbles, props) => { | |
const chunks = [] | |
let i = 0 | |
while (i < strings.length) { | |
chunks.push(strings[i]) | |
chunks.push(typeof bubbles[i] === 'function' ? bubbles[i](props) : bubbles[i]) | |
i += 1 | |
} | |
return chunks.join('') | |
} | |
const hashClassName = stylesheet => { | |
return /* hash */ | |
} | |
const make = key => { | |
return (strings, ...bubbles) => { | |
return (props) => { | |
const stylesheet = generateStylesheet(strings, bubbles, props) | |
const className = hashClassName(stylesheet) | |
return React.createElement(key, {...props, className }) | |
} | |
} | |
} | |
const styled = new Proxy(null, { | |
get(_m, stringKey) { | |
return make(stringKey) | |
}, | |
apply(_, _, [componentType]) { | |
return make(componentType) | |
} | |
}) |
This file contains hidden or 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
import styled, { StyledFunction } from "styled-components" | |
interface YourProps { | |
invalid: boolean | |
} | |
const input: StyledFunction<YourProps & React.HTMLProps<HTMLInputElement>> = styled.input | |
const Input = input` | |
border: ${p => p.invalid ? 'red' : 'blue'}; | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment