classnames-in-js
A more sane approach to CSS in React (and Preact)
When you love the idea of styled-components
and CSS-in-JS
, but you also kind of hate it.
Heavily inspired by how styled-components and emotion lets us write components, but without having to write CSS in JavaScript.
Usage
Installation
npm i classnames-in-js
gzip size | module | tag-api | safeguards (?) | theme context |
---|---|---|---|---|
~3kb |
classnames-in-js |
✅ | ✅ | ✅ |
~0.5kb |
classnames-in-js/lite |
❌ | ❌ | ❌ |
~3kb |
classnames-in-js/preact |
✅ | ✅ | ❌ awaiting context api in Preact X |
~0.4kb |
classnames-in-js/preact-lite |
❌ | ❌ | ❌ |
Basic usage
const Heading = ReactDOM // <h1 class="heading">Hello</h1>
Integrates with CSS modules
const Heading = ReactDOM // <h1 class="heading-lkjfos">Hello</h1>
Conditionally applying classes
If classnames-in-js
recieves a function as the second argument it will be called with the component props and/or theme.
const Heading = ReactDOM // <h1 class="heading-lkjfos heading--dark-lkjfos">Hello</h1>
Appending and overriding
If a consumer passes a className
prop it will be appended.
const Heading = ReactDOM // <h1 class="heading heading--dark">Hello</h1>
const Heading = const DarkHeading = const EvenDarkerHeading = ReactDOM // <h1 class="heading">Hello</h1>// <h1 class="heading heading--dark">Hello</h1>// <h1 class="heading heading--dark heading--even-darker">Hello</h1>
Theming
const Heading = ReactDOM // <h1 class="heading heading--sport">Hello</h1>
Tagged template literal API
classnames-in-js
also supports using tagged template literals to construct classes.
If an interpolated value is a function it will be called with the props
and the theme
if present.
const Heading = styledh1` heading ` ReactDOM // <h1 class="heading heading--dark heading--sport">Hello</h1>
Preact
Note: classnames-in-js/preact
does not currently support automaticly extracting theming from context or the tagged template literal api. This is on the todo list.
See also
License
MIT.