Inline CSS styles in React: how to implement media queries?

You can't. There are certain CSS features, like @media queries, that must be defined in a declaration block in a stylesheet.

While inline CSS is great for most styling attributes that can be applied in key-value pairs, it isn't a complete replacement for dedicated stylesheets.

EDIT:

There are experimental objects available in certain browsers (Chrome 9+, IE 10+, Firefox 6+) that allow you to add event listeners when media queries on the document change, such as MediaQueryList.

There is a nascent React project called Radium that provides mixins for applying conditional styling based on the active media queries, using MediaQueryList under the hood.


You can't do things like media queries and pseudo elements without a stylesheet. You can, however, access the information they're built on in JavaScript. For example, a naive implementation of a resize mixin:

var ResizeMixin = {
    componentDidMount: function(){
        window.addEventListener('resize', this._resize_mixin_callback);
    },
    _resize_mixin_callback: function(){
        this.setState({
            viewport: {
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight
            }
        });
    },
    componentWillUnmount: function(){
        window.removeEventListener('resize', this._resize_mixin_callback);
    }
};

You could then include that in your component, and have a render that looks like this:

render: function(){
  var style;

  if (this.state.viewport.width > 900) {
    style = {width: '45%', margin: '2.5%'};
  }
  else {
    style = {width: '100%', margin: '0'};
  }
  ...
}

I'm not sure this is a good idea, but it can be done.


By 'naive implementation' I mean it has performance problems. addEventListener is actually pretty heavy, so you want to wrap that in a simple js event emitter. You can also have only one instance of the viewport object to save some GC pressure. And you want to throttle the event because browsers will emit it very fast when dragging the window.

As with all good abstractions, you can make these optimizations when you have spare time, and you don't need to modify the components using it.