Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

radium

formidablelabs244.5kMIT0.26.2TypeScript support: definitely-typed

A set of tools to manage inline styles on React elements

readme

Travis Status AppVeyor Status Coverage Status NPM Package Dependency Status gzipped size Maintenance Status

Radium

yarn add radium
# or
npm install --save radium

Radium is a set of tools to manage inline styles on React elements. It gives you powerful styling capabilities without CSS.

Inspired by React: CSS in JS by vjeux.

Maintenance Status

Stable: Formidable is not planning to develop any new features for this project. We are still responding to bug reports and security concerns. We are still welcoming PRs for this project, but PRs that include new features should be small and easy to integrate and should not include breaking changes.

For more about what this means for Radium, view our announcement here.

Overview

Eliminating CSS in favor of inline styles that are computed on the fly is a powerful approach, providing a number of benefits over traditional CSS:

  • Scoped styles without selectors
  • Avoids specificity conflicts
  • Source order independence
  • Dead code elimination
  • Highly expressive

Despite that, there are some common CSS features and techniques that inline styles don't easily accommodate: media queries, browser states (:hover, :focus, :active) and modifiers (no more .btn-primary!). Radium offers a standard interface and abstractions for dealing with these problems.

When we say expressive, we mean it: math, concatenation, regex, conditionals, functions–JavaScript is at your disposal. Modern web applications demand that the display changes when data changes, and Radium is here to help.

For a short technical explanation, see How does Radium work?.

Features

  • Conceptually simple extension of normal inline styles
  • Browser state styles to support :hover, :focus, and :active
  • Media queries
  • Automatic vendor prefixing
  • Keyframes animation helper
  • ES6 class and createClass support

Docs

Usage

Start by wrapping your component class with Radium(), like export default Radium(Component), or Component = Radium(Component), which works with classes, createClass, and stateless components (functions that take props and return a ReactElement). Then, write a style object as you normally would with inline styles, and add in styles for interactive states and media queries. Pass the style object to your component via style={...} and let Radium do the rest!

<Button kind="primary">Radium Button</Button>
import Radium from 'radium';
import React from 'react';
import color from 'color';

class Button extends React.Component {
  static propTypes = {
    kind: PropTypes.oneOf(['primary', 'warning']).isRequired
  };

  render() {
    // Radium extends the style attribute to accept an array. It will merge
    // the styles in order. We use this feature here to apply the primary
    // or warning styles depending on the value of the `kind` prop. Since its
    // all just JavaScript, you can use whatever logic you want to decide which
    // styles are applied (props, state, context, etc).
    return (
      <button style={[styles.base, styles[this.props.kind]]}>
        {this.props.children}
      </button>
    );
  }
}

Button = Radium(Button);

// You can create your style objects dynamically or share them for
// every instance of the component.
var styles = {
  base: {
    color: '#fff',

    // Adding interactive state couldn't be easier! Add a special key to your
    // style object (:hover, :focus, :active, or @media) with the additional rules.
    ':hover': {
      background: color('#0074d9')
        .lighten(0.2)
        .hexString()
    }
  },

  primary: {
    background: '#0074D9'
  },

  warning: {
    background: '#FF4136'
  }
};

Importing Radium

As of v0.22.x, Radium is built as an ECMAScript Modules-first project. We now have a package.json:module entry pointing to our library files with import|export statements instead of CommonJS requires. We still support CommonJS requires with a special package.json:main entry pointing to root index.js to smooth over this transition. The basic takeaways are:

If you are using ESM with webpack or @std/esm with Node.js, imports like the following work fine without any gotchas:

import Radium from 'radium';
import Radium, {Style} from 'radium';

If you are using CommonJS with Node.js or webpack@1 requires work like normal:

const Radium = require('radium');
const {Style} = require('radium');

If you are using CommonJS with webpack@2+, however, you must instead add .default to the root Radium object import:

const Radium = require('radium').default; // CHANGED: Must add `.default`
const {Style} = require('radium'); // Works as per normal

If you cannot change the require statements directly (say Radium is included from a different library your project depends on) you can manually tweak the Radium import in your project's webpack configuration with the following:

resolve: {
  alias: {
    radium: require.resolve('radium/index');
  }
}

which will allow const Radium = require('radium'); to still work. The configuration effectively forces webpack to point to code from package.json:main (which points to /index.js) instead of what is in package.json:module.

Note: Radium uses Reflect which is not supported in IE11. You will need to bring in a polyfill like CoreJs in order to support <IE11.

Examples

To see the universal examples:

npm install
npm run universal

To see local client-side only examples in action, do this:

npm install
npm run examples

How does Radium work?

Following is a short technical explanation of Radium's inner workings:

  • Wrap the render function
  • Recurse into the result of the original render
  • For each element:
    • Add handlers to props if interactive styles are specified, e.g. onMouseEnter for :hover, wrapping existing handlers if necessary
    • If any of the handlers are triggered, e.g. by hovering, Radium calls setState to update a Radium-specific field on the components state object
    • On re-render, resolve any interactive styles that apply, e.g. :hover, by looking up the element's key or ref in the Radium-specific state

More with Radium

You can find a list of other tools, components, and frameworks to help you build with Radium on our wiki. Contributions welcome!

Contributing

Please see CONTRIBUTING

changelog

Radium Changelog

0.26.2

  • Update peerDependencies for React to include 17.

0.26.1 (September 29, 2020)

Dependency Upgrades

  • Bump handlebars from 4.1.2 to 4.5.3 (#1035)
  • Bump elliptic from 6.4.0 to 6.5.3 (#1045)
  • Bump eslint-utils from 1.3.1 to 1.4.3 (#1039)
  • Bump tree-kill from 1.2.0 to 1.2.2 (#1046)
  • Bump websocket-extensions from 0.1.1 to 0.1.4 (#1044)
  • Bump fstream from 1.0.11 to 1.0.12 (#1038)
  • Bump sshpk from 1.11.0 to 1.16.1 (#1037)
  • Bump webpack-dev-server from 2.11.1 to 3.1.11 (#1036)
  • Bump is-my-json-valid from 2.16.0 to 2.20.5 (#1048)
  • Bump http-proxy from 1.16.2 to 1.18.1 (#1047)

Bug Fixes

  • Fix initial enhancer state for fn components (#1041)

0.26.0 (September 5, 2019)

Bug Fixes

  • Add hook and forwardRef support (#1027)

Breaking Changes

0.25.2 (June 7, 2019)

Bug Fixes

  • Bump handlebars from 4.0.6 to 4.1.2 (#1026)
  • Fixed bug with undefined _extraRadiumStateKeys (#1025)
  • Update unitless CSS property list and licensing (#1020)

0.25.1 (December 16, 2018)

Bug Fixes

  • Pass snapshot argument to `componentDidUpdate (#1013)

Infra/Tooling

  • Fix console warnings when running examples (#1002)
  • Upgrade karma to 3.0 (#1003)
  • Refactor enhancer for readability (#1004)
  • Replace Isparta with Istanbul (#1011)
  • Prettier (#1012)

0.25.0 (September 16, 2018)

  • Use Reflect to construct es native classes in a way that preserves the value of this used in the constructor. (#999, #1001)
  • Handle multiple animationName props (#909)

0.24.1 (July 9, 2018)

  • Make <StyleSheet> manually update <style> tag DOM, fixing media queries on component level flickering. (#626, #950)

0.24.0 (March 29, 2018)

  • Fix render methods that return array of children or React.Fragment. (#950)
  • Upgrade tests to React 16.2 (for Fragment support)

0.23.0 (March 15, 2018)

  • Support ES7 arrow functions for React class methods. (#738)

0.22.1 (March 1, 2018)

  • Fix keyframes bug from prefixed inline styles. (#973)

0.22.0 (February 9, 2018)

Breaking Changes

  • Radium now exports defaults as .default, so for runtimes like Node.js for all files in lib/**. We have changed package.json:main to point to /index.js instead of /lib/index.js as a convenience wrapper to expose mostly what was there before so behavior of const Radium = require('radium'); works mostly as it did before. Caveats:
    • When using webpack2+ to build code with require('radium') in it you will need to change that to become require('radium').default.
    • Any imports of a default export from a file in lib like const Enhancer = require('radium/lib/enhancer'); will need to be changed to const Enhancer = require('radium/lib/enhancer').default;.
    • We have a full examples repository of how imports work in all likely scenarios that should come up. https://github.com/FormidableLabs/radium-experiments-v0.22

Features

  • Add es ESM module export files.

Fixes

  • Fix package.json:scripts.postinstall task to correctly work for git-based dependencies.

0.21.2 (January 25, 2018)

  • Fix multiple-value prefixed inline styles. (#962, #958, #951)

0.21.1 (January 18, 2018)

  • Call componentDidUpdate() inherited method (#957).

0.21.0 (January 8, 2018)

  • Automatically clear browser state of elements when unmounting and remounting (#956).
    • resolveStyles returns { extraRadiumStateKeys, element } instead of just element.

0.20.1 (January 8, 2018)

  • Fix v0.20.0 build.

0.20.0 (January 8, 2018)

  • Upgrade inline-style-prefixer to version ^4.0.0.

0.19.6 (October 5, 2017)

  • Allow native ES classes to be used with the Radium enhancer.

0.19.5 (October 5, 2017)

  • Enable React 16 in peerDependencies and update tests to React 16.

0.19.4 (July 21, 2017)

  • Remove .babelrc from published npm registry package.

0.19.3 (July 20, 2017)

  • Remove publishr from prod dependencies in npm registry package.

0.19.2 (July 20, 2017)

  • Switch to publishr workflow. (#894, #731, #900)
  • Remove rimraf from prod dependencies in npm registry package.
  • Remove postinstall from scripts in npm registry package. (#794)

0.19.1 (May 17, 2017)

Bug Fixes

  • Makes prop-types a dependencies instead of a peerDependencies in package.json per the prop-types integration guide.

0.19.0 (May 15, 2017)

Improvements

  • Unreverts PropTypes-related diff, which is now a minor version instead of a patch

0.18.4 (May 15, 2017)

Bug Fixes

  • Reverts PropTypes-related diff, which should have been a minor version instead of a patch

0.18.3 (May 15, 2017)

Improvements

  • Update dependencies
  • Update deprecated React syntax in examples
  • Use React "prop-types" package

0.18.2 (March 15, 2017)

Improvements

  • Update inline-style-prefixer to v2.0.5 (#880).
  • Use React.PureComponent to avoid unnecessary rendering (#868).
  • Update all dependencies

0.18.1 (July 19, 2016)

Bug Fixes

  • Fix unused props warning when passing radiumConfig to StyleRoot (#787).

0.18.0 (July 15, 2016)

Breaking Changes

  • Revert content auto-quoting in Style component (#783).

Bug Fixes

  • Silence React 15.2 unused props deprecation warning (#782).

0.17.2 (July 12, 2016)

Bug Fixes

  • Fix content values in Style component (#719).
  • Improve stateless component check to work with native arrow functions (#771).

Improvements

  • Add support for :disabled pseudo-class (#689).
  • Add plugin to remove nested style objects and prevent [Object object] from rendering in the DOM (#703).

0.17.1 (March 30, 2016)

Bug Fixes

  • Remove babel modules accidentally published as dependencies.

Improvements

  • Add support for scopeSelector without nested selectors in Style component.

0.17.0 (March 24, 2016)

Bug Fixes

  • Upgrade inline-style-prefixer to version 1.0.3 with a fix for display values being removed in IE10.

Improvements

  • Add TestMode for controlling internal Radium state and behavior during tests.

Breaking Changes

  • inline-style-prefixer has updated vendor prefixes, removing some outdated prefixes like -moz-transform.

0.16.6 (February 9, 2016)

Bug Fixes

  • The lib/ directory did not get built property in 0.16.6. lib/ now contains all changes from 0.16.5.

0.16.5 (January 27, 2016)

Bug Fixes

  • Don't merge media query styles, fixes #550
  • Don't add className if empty, fixes #539

Improvements

  • Passing 'all' as the userAgent will add all prefixes, useful for caching server-rendered pages, thanks @oliviertassinari (this applies to inline styles and style rendered as CSS, but does not yet include adding all the prefixed versions of keyframes)
  • Add support for :visited styles:
const url = 'https://github.com/formidablelabs/radium';
const VisitedLink = Radium(() => (
  <a href={url} style={{color: 'gray', ':visited': {color: 'black'}}}>
    {url}
  </a>
));

0.16.4 (January 23, 2016)

Bug Fixes

  • Add px suffix if needed before prefixing, since the list in appendPxIfNeeded does not include prefixed variants
  • Radium now calls toString on values itself, instead of relying on inline-style-prefixer or React to do so (they don't)

Improvements

  • Much lighter npm install radium by removing babel & co from dependencies before publishing
  • Radium now ignores children or props that are themselves Radium enhanced components, for a nice perf gain. Thanks @spacenick

0.16.3 (January 21, 2016)

  • Published under the test tag, so not installable via npm latest
  • Forgot to add -test to the version
  • See changelog for 0.16.4 instead

0.16.2 (January 8, 2016)

Bug Fixes

  • <StyleSheet/> Component:
    • Bind the private method _onChange to the class instance
    • Wrap setState in setTimeout and keep track of isMounted, #500
    • Remove duplicate declaration of componentWillUnmount and move this._isMounted = true inside componentDidMount
  • Clear up docs around StyleRoot props, clear up issues in #496
  • Properly prefix keyframes: Use inline-style-prefixer’s prefixedKeyframes, #488
  • Ensure unique classname is generated for media query rules (hash on query and ruleCSS string)

0.16.1 (January 5, 2016)

Bug Fixes

  • <StyleRoot> no longer throws an error on unmount

0.16.0 (January 5, 2016)

New Features

  • Server-side rendering for media queries and keyframes!

Breaking Changes

Bug Fixes

  • Don't add extra media query listeners
  • Append px to numeric values on properties that don't accept unitless values

Improvements

  • Upgrade inline-style-prefixer to version 0.6.2 (Edge support)
  • Better error on duplicate keys
  • Upgrade to Babel 6
  • <Style> adds the scopeSelector to comma separated selectors
  • <Style> now accepts radiumConfig directly with the userAgent field

0.15.3 (November 16, 2015)

Bug Fixes

  • Fix "files" section in package.json, should fix npm install issues

0.15.2 (November 15, 2015)

Bug Fixes

  • IE vender prefix (ms) is now converted to dash-case correctly (-ms), thanks @PallasKatze, fixes #413
  • Super getChildContext is no longer ignored, thanks @richardfickling, fixes #412
  • Update to inline-style-prefixer v0.5.1 and changed the userAgent error to a console.warning

0.15.1 (November 11, 2015)

Bug Fixes

  • Fix bug where active styles on multiple elements in the same component were not being removed on mouse up, fixes #410

0.15.0 (November 11, 2015)

New Features

  • Radium now uses inline-style-prefixer to do all prefixing. Because inline-style-prefixer relies on the userAgent (similar to autoprefixer), it produces the same prefixes on both the client and the server. This is a huge step in making Radium truly universal (see example). Thanks much to @rofrischmann for putting up with my API suggestions and requests!
  • Any Radium component can also be configured at render time via a radiumConfig. This was mainly required for passing the userAgent during a server-side render.

Breaking Changes

  • Style component no longer supports the prefix prop. It automatically gets the correct userAgent to pass to the prefixer from radiumConfig context

Bug Fixes

  • Radium wrapper now replaces the style propType, if defined, with array or object, fixing #396
  • Stateless components now support context, thanks @ThomWright
  • Static fields on stateless components are now transferred to the Radium wrapper (defualtProps, propTypes, etc)

Improvements

  • Code has been ES2015-ified: const and let, import/export, fat arrows,
  • Code has moved from modules to src

0.14.3 (October 19, 2015)

Bug Fixes

  • camelCasePropsToDashCase handles uppercase first character correctly, fixing #387

0.14.2 (October 17, 2015)

Bug Fixes

  • :active styles now triggered by space or enter
  • Callback refs are now ignored, fixing #346
  • Heavy use of media queries no longer causes setState on an unmounted component, fixing #382

New Features

  • Stateless components (function taking props) are now supported

Improvements

  • Updated examples to for React 0.14.0
  • Allow replacing the prefixer used by Radium.keyframes and <Style>

0.14.1 (September 15, 2015)

Bug Fixes

  • Don't require object-assign, which wasn't in normal dependencies

0.14.0 (September 15, 2015)

Breaking Changes

  • Config.setMatchMedia has been replaced by the matchMedia field in the config passed to @Radium (see documentation)

New Features

Improvements

  • Flatten nested arrays in style, #344, thanks @almost
  • Universal/isomorphic example npm run universal, thanks @jurgob and @moret

Bug Fixes

  • Static properties are now copied again in IE < 10, #349, thanks @bobbyrenwick

0.13.8 (August 24, 2015)

Bug Fixes

  • Fix static class methods disappearing in IE10, #313
  • Fix bug when using spread operator to pass props to a DOM element, #322

0.13.7 (August 5, 2015)

Bug Fixes

  • Fix double resolving bug on props.children, #307

0.13.6 (August 5, 2015)

New Features

  • Resolve styles on elements found in props and children as function, #298
  • <PrintStyleSheet> component and printStyles property to add print styles to your components, #299, thanks @bobbyrenwick

Improvements

  • Show component name when warning in prefixer, #302, thanks @AnSavvides

Bug Fixes

  • Fix bug with _radiumDidResolveStyles that was breaking in React 0.14.0-beta2
  • Un-prefix values before checking isUnitlessNumber, #305, thanks @AnSavvides
  • Prevent errors from getters that do not have setters as static props of React components, #306, thanks @rolandpoulter

0.13.5 (July 29, 2015)

Improvements

  • Support for old and tweener flexbox syntax, #279, thanks @sylvaingi
  • Only calls console.warn during development, not in production

Bug Fixes

  • Don't call resolveStyles more than once on the same element, #293
  • Allow null or undefined values in style, #263
  • Remove redundant babel-core from dependencies
  • Fix using numeric 0 as key to getState, #275
  • Don't wrap display name with "Radium(...)", #271
  • Fix older firefox missing float property, #277, thanks @bencao
  • Don't warn when mixing transform properties, #272, thanks @MattHauglustaine
  • Use for loop instead of Array prototype on the result of window.getComputedStyle, which was breaking Android web view, #267, thanks @bsbeeks
  • Ignore functions as children instead of blowing up, #265, thanks @Cottin

Misc

  • Add test-dev command for faster test feedback during development

0.13.4 (July 14, 2015)

Bug Fixes

  • Fix regression with multiple states (tests were failing) from 0.13.3

0.13.3 (July 13, 2015)

Bug Fixes

  • Fix hotloading component methods, #255, thanks @bobbyrenwick
  • Add displayName to shorthand warning, #253, thanks @bobbyrenwick
  • Warn and ignore null/undefined values, #250, thanks @AnSavvides
  • Don't warn when mixing border & borderRadius, and more shorthand warning updates, #246, thanks @nathanfriemel
  • Remove react from peerDependencies so Radium can be used with the 0.14 beta, #242, thanks @dariocravero
  • Fix transfering defaultProps and friends in IE <11, #241, thanks @bobbyrenwick
  • Don't alias matchMedia, fixes IE <11 bug, #238
  • Stop mutating style state, #237

Misc

  • Migrate tests to Karma, #240, thanks @exogen

0.13.2 (June 25, 2015)

Bug Fixes

  • Use console.warn instead of console.warning (duh)

0.13.1 (June 24, 2015)

New Features

Bug Fixes

  • Don't resolve style prop of custom components, e.g. <MyComponent style={...} />, #202 (thanks @azazdeaz)
  • Fix not using dash-case on server with Style, #207
  • Fix server rendering when using fallback array of values (uses first one)
  • Fix numeric fallbacks, #221

Misc

  • Update dependencies
  • Warn when mixing longhand and shorthand

0.13.0 (June 7, 2015)

Breaking Changes

  • Radium.wrap and Radium.Enhancer have been merged and moved to Radium(). Just wrap your component, Button = Radium(Button);, or use the decorator @Radium
  • Style component rules prop now takes an object instead of an array

New Features

  • Support fallback values (e.g. #fff for rgba(...))

Bug Fixes

  • Fix react external in webpack config
  • Fix keyframes throwing on IE9 (now does feature detection)
  • Fix windows build
  • string and number children are no longer wrapped in an extraneous <span>

0.12.2 (May 22, 2015)

Breaking Changes

None

New Features

  • Support prefixing for old flexbox implementations

Bug Fixes

  • Stop using react internals CSSPropertyOperations.createMarkupForStyles, which further reduces the build size

0.12.1 (May 22, 2015)

Bug Fixes

  • Fix Enhancer (displayName, etc) #165
  • Reduce size of distributed build
  • Tests for prefixing, fix #161

0.12.0 (May 16, 2015)

New Features

  • Support for ES6 classes with Radium.Enhancer
  • Vendor-prefixing
  • Keyframes animation helper
  • Radium.getState API

Bug Fixes

  • Fix errors during server-side rendering #141
  • Fix passing a single child or string #139

0.11.1 (April 28, 2015)

Bug Fixes

  • Checked in updated dist files from 0.11.0. Whoops!

0.11.0 (April 28, 2015)

Breaking Changes

  • Complete API rewrite.
    • Added new "Wrap" API.
    • Wrap React component config with Radium.wrap() to automatically add browser state handlers, media query behavior, and array-based style resolution.
  • Removed all mixins.
  • Removed context-based media query behavior.
    • Replaced with global media query handler.
  • Removed modifiers, states, and media queries from style objects.
    • Replaced modifiers with array-based style prop resolution.
    • Replaced states object with inline state keys: :hover
    • Replaced mediaQueries object with inline queries: @media (min-width: 200px)

New Features

  • Apply separate browser state styles to multiple elements in the same component.