Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created January 25, 2022 01:12
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 mattmccray/17f9f8fbdf9143e20c6a6e56799faf8c to your computer and use it in GitHub Desktop.
Save mattmccray/17f9f8fbdf9143e20c6a6e56799faf8c to your computer and use it in GitHub Desktop.
Simple Component wrapper for use with SolidJS and ./css.ts
import { JSX } from "solid-js"
import { Dynamic } from 'solid-js/web'
export interface ComponentProps { children?: any, className?: string, [attr: string]: any }
export type CssComponent = (props: ComponentProps) => JSX.Element
export function component(styles: string): CssComponent
export function component(tag: string | CssComponent, styles: string): CssComponent
export function component(tag?: string | CssComponent, styles?: string): CssComponent {
let extraClassNames = ''
if (!styles) {
if (typeof tag !== 'string') throw new Error("No styles provided")
styles = tag
tag = 'div'
}
if (typeof tag === 'string' && tag.includes('.')) {
const parts = tag.split('.')
tag = parts.shift()
extraClassNames = parts.join(' ')
}
return (props: ComponentProps) => {
const { className = '', children, ...attrs } = props
const combinedClassName = `${extraClassNames} ${styles} ${className}`
return tag === 'div'
? <div {...attrs} className={combinedClassName}>{props.children}</div>
: <Dynamic component={tag} {...attrs} className={combinedClassName}>{props.children}</Dynamic>
}
}
const Simple = component(css`
& { color: green; }
`)
const Other = component('article', css`
& { color: black; }
`)
const MiniButton = component('button.btn-mini', css`
& { color: red; }
`)
const LargeButon = component(MiniButton, css`
& { color: dodgerblue; }
`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment