All Projects → jamesknelson → react-cx

jamesknelson / react-cx

Licence: MIT License
Combine styles from CSS Modules with a `cx` prop.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-cx

postcss-gtk
Processes GTK+ CSS into browser CSS
Stars: ✭ 23 (-4.17%)
Mutual labels:  style
glitz
Lightweight CSS-in-JS library with high performance written in TypeScript
Stars: ✭ 42 (+75%)
Mutual labels:  style
PyQtDarkTheme
A flat dark theme for PySide and PyQt.
Stars: ✭ 50 (+108.33%)
Mutual labels:  style
Daft-Exprt
PyTorch Implementation of Daft-Exprt: Robust Prosody Transfer Across Speakers for Expressive Speech Synthesis
Stars: ✭ 41 (+70.83%)
Mutual labels:  style
css-render
Generating CSS using JS with considerable flexibility and extensibility, at both server side and client side.
Stars: ✭ 137 (+470.83%)
Mutual labels:  style
react-native-highlighted-text
A React Native component to individually style texts inside a text
Stars: ✭ 18 (-25%)
Mutual labels:  style
PlantUML-colors
This script is to show all named color suggested by PlantUML
Stars: ✭ 52 (+116.67%)
Mutual labels:  style
terminal-style
🎨 Return your terminal message in style! Change the text style, text color and text background color from the terminal, console or shell interface with ANSI color codes. Support for Laravel and Composer.
Stars: ✭ 16 (-33.33%)
Mutual labels:  style
QSvgStyle
QSvgStyle is a themeable SVG style for Qt5 applications
Stars: ✭ 66 (+175%)
Mutual labels:  style
prettier-check
Check that all files match prettier code style.
Stars: ✭ 54 (+125%)
Mutual labels:  style
CompositeToggle
Composite toggle system for unity
Stars: ✭ 38 (+58.33%)
Mutual labels:  style
vue-component-style
A Vue mixin to add style section to components.
Stars: ✭ 16 (-33.33%)
Mutual labels:  style
DiscordFX
DocFX template to create documentation similar to Discord
Stars: ✭ 26 (+8.33%)
Mutual labels:  style
markdown.css
📝 The simple CSS to replicate the GitHub Markdown style (Sukka Ver.)
Stars: ✭ 13 (-45.83%)
Mutual labels:  style
osmicsx
An utility style framework for React Native
Stars: ✭ 162 (+575%)
Mutual labels:  style
tsstyled
A small, fast, and simple CSS-in-JS solution for React.
Stars: ✭ 52 (+116.67%)
Mutual labels:  style
Prestyler
Elegant text formatting tool in Swift 🔥
Stars: ✭ 36 (+50%)
Mutual labels:  style
HandySub
Download Subtitle from Subscene and other sources
Stars: ✭ 42 (+75%)
Mutual labels:  style
tYp3r
😎 dA aNn0Y1Ng t3Xt g3NeRa7or (The annoying text generator :-P)
Stars: ✭ 30 (+25%)
Mutual labels:  style
codemirror-colorpicker
colorpicker with codemirror
Stars: ✭ 113 (+370.83%)
Mutual labels:  style

react-cx

Version

Add styles from CSS Modules with a cx prop:

<div
  cx={['Arrow', { active }, color, 'length-'+length]}
  className={className}
 />

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 names
import styles from './Theme.less'

export function({ active, className, color, length=1 }) {
  const className = `
    ${styles.Arrow}
    ${active ? styles.active : ''}
    ${styles[color] || ''}
    ${styles['length-+'length] || ''}
    ${className}
  `
  <div className={className} />
}

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` strings
import bindClassNames from 'classnames/bind'
const cx = bindClassNames(styles)

export function Arrow({ active, className='', color, length=1 }) {
  return <div className={cx('Arrow', { active }, color, 'length-'+length)+' '+className} />
}

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 = getReactWithCX(styles)

export function Arrow({ active, className, color, length=1 }) {
  return (
    <div
      cx={['Arrow', { active }, color, 'length-'+length]}
      className={className}
     />
  )
}

Of course, the cx prop can also accept strings or plain objects:

export function Switch({ active, className, color='lifecycle', direction='down' }) {
  return (
    <div cx={['Switch', { active }, color, direction]} className={className}>
      <div cx="pivot" />
      <Arrow active={active} color={color} />
    </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.

import UnprefixedReact from 'react'
import classnames from 'classnames/bind'

export default function cx(styles, prop='cx') {
  const bound = classnames.bind(styles)

  function getProps(props) {
    if (!props) return props

    if (props.cx) {
      const result = Object.assign({}, props)
      delete result.cx
      const args = Array.isArray(props.cx) ? props.cx : [props.cx]
      result.className = bound(...args)
      if (props.className) result.className += ' '+props.className
      return result
    }
    return props
  }
  function createElement(type, props, ...children) {
    return UnprefixedReact.createElement(type, getProps(props), ...children)
  }
  function cloneElement(element, props, ...children) {
    return UnprefixedReact.cloneElement(element, getProps(props), ...children)
  }
  return Object.assign({}, UnprefixedReact, {
    createElement,
    cloneElement
  })
}

More examples

These components are all taken from my React lifecycle simulators.

export function Indicator({ active, className, color, icon, label, noMobile, scheduled, style }) {
  return (
    <div cx={['Indicator', (scheduled || active) && color, { active, 'no-mobile': noMobile }]} className={className} style={style}>
      { icon &&
        <div cx="icon">{icon}</div>
      }
      <div cx="label">{label}</div>
    </div>
  )
}

export function Switch({ active, className, color='lifecycle', direction='down', style }) {
  return (
    <div cx={['Switch', { active }, color, direction]} className={className} style={style}>
      <div cx="pivot" />
      <Arrow active={active} color={color} headless={direction === 'down'} />
    </div>
  )
}

function SwitchedSetter({ className, color, icon, label, noMobile, setActive, style, switchActive, willSet }) {
  return (
    <div cx={['SwitchedSetter', { 'no-mobile': noMobile }]} className={className} style={style}>
      <Switch active={switchActive} direction={willSet ? 'right' : 'down' } />
      <Indicator active={setActive} color={color} icon={icon} label={label} scheduled={willSet} />
      <Arrow cx='horizontal-wire' active={setActive} color={color} headless length={4} />
      <Arrow cx='vertical-wire' active={setActive} color={color} headless />
      <Arrow cx='output' active={setActive || (switchActive && !willSet)} color={switchActive ? 'lifecycle' : color} />
    </div>
  )
}

License

MIT Copyright © 2017 James K Nelson

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].