react-cx
Add styles from CSS Modules with a cx
prop:
<div = = />
Inspired by jareware/css-ns. Uses jedwatson/classnames under the hood.
Install with npm:
# Adds react-cx to node_modules and package.json npm install react-cx --save
Why?
When styling components with CSS modules, you'll often need join multiple class names together before passing them to the React className
prop.
// CSS Modules provide an object with your stylesheet's class namesimport styles from './Theme.less' { const className = ` ` <div = />}
The classnames package can help, but the resulting code still feels a little verbose after you've typed it for the 50th time.
import styles from './Theme.less' // classnames provides a helper to build `className` stringsimport bindClassNames from 'classnames/bind'const cx = { return <div = />}
With react-cx, you can add styles from your CSS modules directly to your elements by using the cx
prop. It uses the same syntax as the classnames package, and still lets you append a raw className
prop.
import styles from './Theme.less' // react-cx adds a `cx` prop to React by wrapping `React.createElement`import getReactWithCX from './react-cx'const React = { return <div = = /> }
Of course, the cx
prop can also accept strings or plain objects:
{ return <div = => <div ="pivot" /> <Arrow = = /> </div> }
These components are taken from my React lifecycle simulators.
How does it work?
In React, JSX calls are translated to calls to React.createElement()
. Thus, by wrapping React.createElement()
with our own function, we can add support for new props without ever touching React's internals.
If you understand how React.createElement()
works, the easiest way to grok this is to just view the source below. If you're not yet familiar with React.createElement()
, head over to React Armory for a simple explanation with live examples and exercises.
{ const bound = classnames { if !props return props if propscx const result = Object delete resultcx const args = Array ? propscx : propscx resultclassName = if propsclassName resultclassName += ' '+propsclassName return result return props } { return UnprefixedReact } { return UnprefixedReact } return Object}
More examples
These components are all taken from my React lifecycle simulators.
{ return <div = = => icon && <div ="icon">icon</div> <div ="label">label</div> </div> } { return <div = = => <div ="pivot" /> <Arrow = = = /> </div> } { return <div = = => <Switch = = /> <Indicator = = = = = /> <Arrow ='horizontal-wire' = = = /> <Arrow ='vertical-wire' = = /> <Arrow ='output' = = /> </div> }
License
MIT Copyright © 2017 James K Nelson