Create reusable and extensible style class variants
npm install class-variant* β‘οΈ Ultra-lightweight ~1.5KB, powered by Proxy
* π‘οΈ Type safety
* π Dynamically change styles based on properties
* π« Re-expand existing elements, like NextLink
* π§© Compatible with server and client components
* πͺ Built-in first-class clsx handling
tsx
function Button(props) {
return (
)
}
`
π₯³ After: It's in one line and ~80% code less.
`tsx
import styled from '@master/styled.react' // or .vueconst Button = styled.button
inline-flex font:14
`
Apply it as usual:
`tsx
export default function App() {
return (
)
}
`
It will be rendered as:
`html
`Getting Started
Install the package depending on your framework:$3
`bash
npm install class-variant
`
`js
import cv from 'class-variant'const btn = cv(...params)
const btn = cv
... // orbtn(props) // -> string
`$3
`bash
npm install @master/styled.react
`
`js
import styled from '@master/styled.react'const Button = styled.button(...params)
const Button = styled.button
... // or`$3
`bash
npm install @master/styled.vue
`
`js
import styled from '@master/styled.vue'const Button = styled.button(...params)
const Button = styled.button
... // or`Basic usage
$3
Declared in two ways: function or template literal, and parameters inherit all features of clsx.
`tsx
const Element = styled.divflex text:center
const Element = styled.div('flex text:center') // orreturn (
Hello World
)
`
`html
Hello World
`$3
Predefine the class variant corresponding to the property.
`tsx
const Button = styled.button('flex', {
$size: {
sm: 'font:12 size:8x',
md: 'font:14 size:12x'
},
disabled: 'opacity:.5',
...
})return (
)
`
`html
`
> β οΈ Custom properties that are not element-owned properties must be prefixed with $prop, otherwise they will be reflected on the final element and an error may be thrown.You can set default properties for elements.
`tsx
Button.default = {
$size: 'md'
}return (
)
`
`html
`$3
Dynamically apply class names based on function properties.
`tsx
const Element = styled.div('fg:white',
({ $color }) => $color && bg:${$color}
)return (
)
`
`html
`$3
Applies the target class name matching all specified property keys and their values.
`tsx
const Button = styled.button('inline-flex',
['uppercase', { $intent: 'primary', $size: 'md' }]
)return (
)
`
`html
`Extended
$3
Extend an existing styled element and add additional classes or conditions.
`tsx
const A = styled.p('a')
const B = styled.p(A)breturn (
A
B
)
`
`html
A
B
`
It also supports client components, taking Next.jsβs Link as an example:
`tsx
'use client'import styled from '@master/styled.react';
import Link from 'next/link';
const Button = styled(Link)
inline-flex text:centerreturn (
)
`
> β οΈ If the extended target contains client components, the 'use client' directive is required.$3
Changing the original tag name of an element, such as