Skip to content

Instantly share code, notes, and snippets.

@EnixCoda
Last active October 14, 2019 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EnixCoda/9c480a73415fd8b37e4a7b101a7443b9 to your computer and use it in GitHub Desktop.
Save EnixCoda/9c480a73415fd8b37e4a7b101a7443b9 to your computer and use it in GitHub Desktop.
simple styled-components
/*
* 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)
}
})
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