Skip to content

Instantly share code, notes, and snippets.

@queckezz
Last active December 8, 2015 11:21
Show Gist options
  • Save queckezz/e3ae09626caefdaf5b62 to your computer and use it in GitHub Desktop.
Save queckezz/e3ae09626caefdaf5b62 to your computer and use it in GitHub Desktop.
CSS in javascript with redux

Overview

After a style dispatch, the middleware hashes the style object and looks up if its already in the cache. If not, add the given classname to the document and add it to the cache:

  • Dispatch action to store { type: '...', payload: { ...styles }}
  • Hash StyleObject -> '646efd54'
  • Check if style is already in cache
  • Store renders style to client (or could be anything: server-side to string etc.)
  • Return hash
import { applyMiddleware, createStore } from 'redux'
import { cssMiddleware, configureStyles, toString } from 'redux-style'
import { em } from 'style-utils'
const createStoreWithMiddleware = applyMiddleware(
cssMiddleware(toString)
)
const store = createStoreWithMiddleware(createStore)
const displayFlex = () => ({ display: 'flex' })
const contain = (width = 56) => ({
max-width: em(containerWidth),
overflow: 'hidden'
})
const styles = configureStyles(store.dispatch, {
displayFlex,
contain
})
render(
h('div', { style: join(' ', [displayFlex, contain(52)]) }, [
h('p', 'A Paragraph')
]),
document.body
)
const styleAction = style => ({
type: '@redux-style/STYLE',
payload: style
})
// configures each style function to dispatch an action with the given style object.
// Function -> StyleObject -> Action
const configureStyles = (dispatch, obj) => {
return map(
(key, fn) => ({
[key]: dispatch(styleAction(fn(...args)))
}),
obj
)
}
export {
configureStyles
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment