• Stars
    star
    122
  • Rank 281,838 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Transforms CSS-alike text into a React style JSON object

react-styling

npm version npm downloads build status coverage

Is a helper function to convert various CSS syntaxes into a React style JSON object

Autoprefixing

This library doesn't perform CSS autoprefixing. Use postcss autoprefixer for that.

Installation

$ npm install react-styling

Usage

This module uses an ES6 feature called template strings which allows you to write multiline strings (finally). You can still use this module with the old ES5 (regular javascript) syntax passing it a regular string, but it's much more convenient for you to just use Babel for ES6 to ES5 conversion (everyone out there does it by the way).

import React from 'react'
import styler from 'react-styling'

export default class Page extends React.Component
{
  render()
  {
    return (
      <div>
        <header>
          <ul style={style.menu}>
            <li style={style.menu.item}><Link to="login" style={style.menu.item.link} activeStyle={style.menu.item.link.current}>Login</Link></li>
            <li style={style.menu.item}><Link to="about" style={style.menu.item.link} activeStyle={style.menu.item.link.current}>About</Link></li>
          </ul>
        </header>

        <RouteHandler/>
      </div>
    )
  }
}

const style = styler
`
  menu
    list-style-type: none

    item
      display: inline-block

      link
        display         : inline-block
        text-decoration : none
        color           : #000000
        padding         : 0.4em

        // notice the ampersand character here:
        // this feature is called a "modifier" class 
        // (see the "Modifiers" section of this document)
        &current
          color            : #ffffff
          background-color : #000000

  // supports comma separated style classes
  // and further style class extension
  
  can_style, multiple_classes, at_once
    font-family : Sans

  can_style
    font-size : 12pt

  multiple_classes, at_once
    font-size : 8pt

  /*
  multi
  line
  comment
  */

  .old-school-regular-css-syntax {
    box-sizing: border-box;
    color: black;
  }

  .scss_less {
    color: white;

    &:hover {
      text-decoration: underline;
    }
  }

  curly_braces_fan {
    background: none

    curly_braces_fan_number_two {
      background: transparent
    }
  }

  YAML_fan:
    display: inline-block

    python:
      length: 99999px

  // for Radium users
  @media (min-width: 320px)
    width: 100%

    :hover 
      background: white
`

The example is self-explanatory. The CSS text in the example above will be transformed to this JSON object

{
  menu:
  {
    listStyleType: 'none',

    item:
    {
      display: 'inline-block',

      link:
      {
        display        : 'inline-block',
        textDecoration : 'none',
        color          : '#000000',
        padding        : '0.4em',

        current:
        {
          display         : 'inline-block',
          textDecoration  : 'none',
          color           : '#ffffff',
          backgroundColor : '#000000',
          padding         : '0.4em'
        }
      }
    }
  },

  can_style:
  {
    fontFamily : 'Sans',
    fontSize   : '12pt'
  },

  multiple_classes:
  {
    fontFamily : 'Sans',
    fontSize   : '8pt'
  },
  
  at_once:
  {
    fontFamily : 'Sans',
    fontSize   : '8pt'
  },

  'old-school-regular-css-syntax':
  {
    boxSizing: 'border-box',
    color: 'black'
  },

  scss_less:
  {
    color: 'white',

    ':hover' 
    {
      color: 'white',
      textDecoration: 'underline'
    }
  },

  curly_braces_fan:
  {
    background: 'none',

    curly_braces_fan_number_two:
    {
      background: 'transparent'
    }
  },

  YAML_fan:
  {
    display: 'inline-block',

    python:
    {
      length: '99999px'
    }
  },

  '@media (min-width: 320px)': 
  {
    width: '100%',

    ':hover': 
    {
      background: 'white'
    }
  }
}

And that's it. No fancy stuff, it's just what this module does. You can then take this JSON object and use it as you wish.

Pay attention to the tabulation as it's required for the whole thing to work properly. If you're one of those people who (for some strange reason) prefer spaces over tabs then you can still use it with spaces. Again, make sure that you keep all your spacing in order. And you can't mix tabs and spaces.

You can use your good old pure CSS syntax with curly braces, semicolons and dotted style class names (in this case the leading dots in CSS style class names will be omitted for later JSON object keying convenience).

Curly braces are a survival from the dark ages of 80s and the good old C language. Still you are free to use your curly braces for decoration - they'll simply be filtered out.

You can also use YAML-alike syntax if you're one of those Python people.

You can use both one-line comments and multiline comments.

Nesting

In the example above the result is a JSON object with a nested tree of CSS style classes. You can flatten it if you like by using import { flat as styler } from 'react-styling' instead of the default import styler from 'react-styling'.

The difference is that the flat styler will flatten the CSS style class tree by prefixing all the style class names accordingly.

The reason this feature was introduced is that, for example, Radium would give warnings if a style object contained child style objects.

Also, I noticed that React, given a style object containing child style objects, creates irrelevant inline styles, e.g. <span style="color: black; child_style_object_name: [Object object]; background: white"/>: it doesn't break anything, but if some day React starts emitting warnings for that then just start using the flat styler.

Modifiers

In the example above, notice the ampersand before the "current" style class - this feature is optional (you don't need to use it at all), and it means that this style class is a "modifier" and all the style from its parent style class will be included in this style class. In this example, the padding, color, display and text-decoration from the "link" style class will be included in the "current" style class, so it works just like LESS/SASS ampersand. If you opt in to using the "modifiers" feature then you won't need to do manual merging like style="extend({}, style.menu.item.link, style.menu.item.link.current)".

Modifiers, when populated with the parent's styles, will also be populated with all the parent's pseudo-classes (those ones starting with a colon) and media queries (those ones starting with an at). This is done for better and seamless integration with Radium.

Modifiers are applied all the way down to the bottom of the style subtree and, therefore, all the child styles are "modified" too. For example, this stylesheet

original
  display : inline-block

  item
    border : none
    color  : black

  &active
    item
      color      : white
      background : black

will be transformed to this style object

original:
{
  display: 'inline-block',

  item:
  {
    border : 'none',
    color  : 'black'
  },

  active:
  {
    display: 'inline-block',

    item:
    {
      border     : 'none',
      color      : 'white',
      background : 'black'
    }
  }
}

Shorthand style property expansion

A request was made to add shorthand style property expansion feature to this library. The motivation is that when writing a CSS rule like border: 1px solid red in a base class and then overriding it with border-color: blue in some modifier class (like :hover) it's all merged correctly both when :hover is added and when :hover is removed. In React though, style rule update algorythm is not nearly that straightforward and bulletproof, and is in fact a very basic one which results in React not handling shorhand CSS property updates correctly. In these cases a special flavour of react-styling can be used:

import { expanded as styler } from 'react-styling'

styler `
  margin: 10px
  border: 1px solid red
`

Which results in the following style object

{
  marginTop    : '10px',
  marginBottom : '10px',
  marginLeft   : '10px',
  marginRight  : '10px',

  borderTopWidth: '1px',
  borderTopStyle: 'solid',
  borderTopColor: 'red',
  // etc
}

Radium

There's a (popular) thing called Radium, which allows you to (citation):

  • Browser state styles to support :hover, :focus, and :active
  • Media queries
  • Automatic vendor prefixing
  • Keyframes animation helper

You can use react-styling with this Radium library too: write you styles in text, then transform the text using react-styling into a JSON object, and then use that JSON object with Radium. If you opt in to use the "modifiers" feature of this module then you won't have to write style={[style.a, style.a.b]}, you can just write style={style.a.b}.

Here is the DroidList example from Radium FAQ rewritten using react-styling. Because first and last are "modifiers" here the :hover pseudo-class will be present inside each of them as well.

// Notice the use of the "flat" styler as opposed to the default one:
// it flattens the nested style object into a shallow style object.
import { flat as styler } from 'react-styling'

var droids = [
  'R2-D2',
  'C-3PO',
  'Huyang',
  'Droideka',
  'Probe Droid'
]

@Radium
class DroidList extends React.Component {
  render() {
    return (
      <ul style={style.droids}>
        {droids.map((droid, index, droids) =>
          <li key={index} style={index === 0 ? style.droid_first : index === (droids.length - 1) ? style.droid_last : style.droid}>
            {droid}
          </li>
        )}
      </ul>
    )
  }
}

const style = styler`
  droids
    padding : 0

  droid
    border-color : black
    border-style : solid
    border-width : 1px 1px 0 1px
    cursor       : pointer
    list-style   : none
    padding      : 12px

    :hover
      background : #eee

    &first
      border-radius : 12px 12px 0 0

    &last
      border-radius : 0 0 12px 12px
      border-width  : 1px
`

Performance

In the examples above, react-styling transforms style text into a JSON object every time a React component is instantiated and then it will reuse that JSON style object for all .render() calls. React component instantiation happens, for example, in a for ... of loop or when a user navigates a page. I guess the penalty on the performance is negligible in this scenario. Yet, if someone wants to play with Babel they can write a Babel plugin (similar to the one they use in Relay) and submit a Pull Request.

Contributing

After cloning this repo, ensure dependencies are installed by running:

npm install

This module is written in ES6 and uses Babel for ES5 transpilation. Widely consumable JavaScript can be produced by running:

npm run build

Once npm run build has run, you may import or require() directly from node.

After developing, the full test suite can be evaluated by running:

npm test

While actively developing, one can use (personally I don't use it)

npm run watch

in a terminal. This will watch the file system and run tests automatically whenever you save a js file.

When you're ready to test your new functionality on a real project, you can run

npm pack

It will build, test and then create a .tgz archive which you can then install in your project folder

npm install [module name with version].tar.gz

License

MIT

More Repositories

1

libphonenumber-js

A simpler (and smaller) rewrite of Google Android's libphonenumber library in javascript
JavaScript
2,520
star
2

webpack-isomorphic-tools

Server-side rendering for your Webpack-built applications (e.g. React)
JavaScript
1,260
star
3

react-phone-number-input

React component for international phone number input
JavaScript
882
star
4

universal-webpack

Isomorphic Webpack: both on client and server
JavaScript
687
star
5

javascript-time-ago

International highly customizable relative date/time formatting
JavaScript
362
star
6

read-excel-file

Read *.xlsx files in a browser or Node.js. Parse to JSON with a strict schema.
JavaScript
275
star
7

webpack-react-redux-server-side-render-example

A sample React/Redux/Webpack project with Server-Side Rendering
JavaScript
250
star
8

react-pages

A complete solution for building a React/Redux application: routing, page preloading, (optional) server-side rendering, asynchronous HTTP requests, document metadata, etc.
JavaScript
179
star
9

webapp

web application boilerplate (React, Redux, React-router, i18n, isomorphic, etc)
JavaScript
124
star
10

virtual-scroller

A component for efficiently rendering large lists of variable height items
JavaScript
122
star
11

react-time-ago

Localized relative date/time formatting in React
JavaScript
96
star
12

react-responsive-ui

Responsive React UI components
JavaScript
69
star
13

relative-time-format

A convenient `Intl.RelativeTimeFormat` polyfill
JavaScript
62
star
14

require-hacker

Provides a hooking mechanism for Node.js require() calls
JavaScript
62
star
15

country-flag-icons

Vector (*.svg) country flag icons in 3x2 aspect ratio
HTML
62
star
16

anychan

A universal web client for online discussion services like "forums" or "imageboards".
JavaScript
50
star
17

input-format

Formatting user's text input on-the-fly
JavaScript
27
star
18

jquery-full-house

(obsolete, deprecated) fills an html block with predefined text, so that font size automatically adjusts itself to the maximum
HTML
15
star
19

es6-tree-shaking-test

Tests whether your ES6-aware module bundler actually performs "tree shaking" (unused code elimination)
JavaScript
14
star
20

imageboard

An easy uniform wrapper over the popular imageboards' API
JavaScript
13
star
21

easy-react-form

Simple, fast and easy-to-use React Form.
JavaScript
13
star
22

write-excel-file

Write simple *.xlsx files in a browser or Node.js
JavaScript
12
star
23

react-website-basic-example

`react-website` basic example
JavaScript
12
star
24

wheely-ios-test

A test for iOS developer position at Wheely
Objective-C
9
star
25

web-service

Instantiates web services: REST Api, file upload, etc
JavaScript
6
star
26

sociopathy

an unusual social network
JavaScript
5
star
27

serverless-functions

Serverless functions toolkit (e.g. AWS Lambda)
JavaScript
2
star
28

social-components-parser

Parses post content
JavaScript
2
star
29

on-scroll-to

A DOM Element that triggers an action whenever it's scrolled into viewport
JavaScript
2
star
30

react-website-webpack-example

An example of using `react-website` with Webpack
JavaScript
1
star
31

react-pages-basic-example

`react-pages` basic example
JavaScript
1
star
32

chartogram

Charts in JS with no dependencies
JavaScript
1
star
33

webapp-db

JavaScript
1
star
34

webapp-backend

JavaScript
1
star
35

print-error

Javascript print error stack trace (pretty, terminal, html, markdown, etc)
JavaScript
1
star
36

simple-http-file-server

A simple HTTP static file server
JavaScript
1
star
37

deviantart_photo_stream

DeviantArt powered digital signage for your second display
JavaScript
1
star
38

react-sortable-dnd-list

A sortable Drag&Drop list React component
JavaScript
1
star
39

halt-hammerzeit.github.io

HTML
1
star