Adding New Utilities

Extend xstyled with your own utilities.

xstyled presents a large collection of utilities to style a complete website. It also exposes a powerful API to be able to create your own utilities.

Create and use a new utility

Let's say you want be able to use a new property not already exposed by xstyled, for example border-inline.

Using style, you can create the property:

// border-inline.js import { style } from '@xstyled/...' export const borderInline = style({ prop: 'borderInline', })

And create a utility namespace y that extend x:

// y.js import { x } from '@xstyled/...' import { borderInline } from './border-inline' const y = x.extend(borderInline) export default y

And use your new extended x:

import y from './y' function App() { return <y.div borderInline="1px dotted blue" /> }

Use a custom prop

By default prop defines both the utility prop and the CSS property generated by the utility. You may want to use another prop, a shortname or something more explicit.

The cssProperty option let you distinct the prop from the CSS property.

import { style } from '@xstyled/...' export const borderInline = style({ prop: 'bi', cssProperty: 'borderInline' }) // Usage <y.div bi="1px dotted blue" />

Alias property

prop accepts a string or an array of strings. It makes it easy to create aliases like margin and m.

import { style } from '@xstyled/...' export const margin = style({ prop: ['margin', 'm'], cssProperty: 'margin', })

Bind property to a primitive

If your property is define by a unit or by a primitive, you should bind it to the primitive. To do that, you have to specify themeGet:

import { style, getColor } from '@xstyled/...' export const borderInlineColor = style({ prop: 'borderInlineColor', themeGet: getColor, }) // Usage <y.div borderInlineColor="red-500" />

Available primitives: getAngle, getAnimation, getBorderColor, getBorderStyle, getBorderWidth, getBorder, getColor, getDuration, getFontSize, getFontWeight, getFont, getInset, getLetterSpacing, getLineHeight, getPercent, getPx, getRadius, getRingWidth, getShadow, getSize, getSpace, getTimingFunction, getTransform, getTransitionProperty, getTransition and getZIndex.

Multi CSS properties

cssProperty accepts a string or an array of strings. It let you create properties like px.

import { style } from '@xstyled/...' export const px = style({ prop: ['px'], cssProperty: ['paddingTop', 'paddingBottom'], })

Generate arbitrary style

Specify a function in cssProperty to define arbitrary style. It makes it easy to create advanced utility like clearfix.

import { style } from '@xstyled/...' export const clearfix = style({ prop: 'clearfix', cssProperty: () => ({ '&::after': { display: 'block', content: '', clear: 'both', }, }), })
Edit this page on GitHub