use-sx
CSS-in-JS, inside out and upside down.
What if?
What if instead of mapping selectors-to-properties-to-values...
<button =>
You mapped properties-to-selectors-to-values?
<Button =>
If your css attributes could accept functions as values, you could even specify colors for all states in a single theme object...
<Button =>
And what if instead of tying your pseudo-selectors to individual elements:
<button =>
You could specified a control boundary, and nested elements would automatically place the :hover
selector where it makes sense?
<ButtonControl => <Icon = = /> <Caret = /></ButtonControl>
If you could create custom style properties, you could even compose your styled components without a care for where they'll eventually be used...
<LinkControl ='/start'> <ButtonBody => <ButtonContent = ="Play" = /> </ButtonBody></LinkControl>
See this as a live example.
How it works
It's just a hook.
This package gives you a useSx()
hook that takes styles in the format of the sx
prop above, and returns styles in the format expected by a css
prop -- as supported by Styled Components.
Note: Currently, the useSx
hook requires Styled Components, as it reads directly from the styled-components theme
context. Support for emotion would make a great Pull Request! 😉
useSx(options)
Basic usage
const Button = React // Then render your component like any otherReactDOM
Mapped props
By passing a maps
property to useSx
, you can add custom style properties to your components. These custom properties can then be used with theme functions and selector objects -- just as with standard CSS properties.
For example, this <Caret>
component accepts three custom style props:
color
, which maps directly to theborderTopColor
propdirection
, which maps to varying rotate transformssize
, which setsborderWidth
and a corresponding negative margin
const Caret = React ReactDOM
control(StyledComponent)
This is a Higher Order Function which expects a Styled Component, returning an identical component that acts as a control boundary -- i.e. the component to which :hover
pseudoselectors on nested elements will be applied.
mergeSx(sx)
This function merges anything that can be passed into the sx
option for useSx
into a single object.
const mergedSx = console // black
This comes in handy when creating composite components that accept an sx
prop, and pass individual style properties down to specific children.
For example, here's how you might use mergeSx()
to extract the color
style from a <ButtonContent>
component's props, and pass it down to nested <Icon>
and <Caret>
elements:
const ButtonContent = React
License
MIT licensed.