• Stars
    star
    1,704
  • Rank 27,394 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 7 months ago

Reviews

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

Repository Details

Use CSS-in-JavaScript with themes for React without being tightly coupled to one implementation

Maintenance Mode: This project is currently in maintenance mode and will eventually be archived. More info


react-with-styles Version Badge

License Downloads

npm badge

Use CSS-in-JavaScript for your React components without being tightly coupled to one implementation (e.g. Aphrodite, Radium, or React Native). Easily access shared theme information (e.g. colors, fonts) when defining your styles.

Interfaces

Other resources

How to use

Step 1. Define your theme

Create a module that exports an object with shared theme information like colors.

export default {
  color: {
    primary: '#FF5A5F',
    secondary: '#00A699',
  },
};

Step 2. Choose an interface

You will need to choose the react-with-styles interface that corresponds to the underlying CSS-in-JS framework that you use in your app. Look through the list of existing interfaces, or write your own!

If you choose to write your own, the interface must implement the following functions:

Function Description
create Function that outputs the styles object injected through props.
(Optional, but required if createLTR is not provided).
createLTR LTR version of create.
(Required, unless a create function is provided)
createRTL RTL version of create.
(Required, unless a create function is provided)
resolve This is the css function that is injected through props. It outputs the attributes used to style an HTML element.
(Optional, but required if no resolveLTR is provided)
resolveLTR LTR version of resolve.
(Required, unless the resolve function is provided)
resolveRTL RTL version of resolve.
(Required, unless the resolve function is provided)
flush? Flush buffered styles before rendering. This can mean anything you need to happen before rendering.
(Optional)

Step 3. Register the chosen theme and interface

Option 1: Using React Context (recommended)

☝️ Requires React 16.6+

As of version 4.0.0, registering the theme and interface can be accomplished through React context, and is the recommended way of registering the theme, interface, and direction.

For example, if your theme is exported by MyTheme.js, and you want to use Aphrodite through the react-with-styles-interface-aphrodite interface, wrap your application with the WithStylesContext.Provider to provide withStyles with that interface and theme:

import React from 'react';
import WithStylesContext from 'react-with-styles/lib/WithStylesContext';
import AphroditeInterface from 'react-with-styles-interface-aphrodite';
import MyTheme from './MyTheme';

export default function Bootstrap({ direction }) {
  return (
    <WithStylesContext.Provider
      value={{
        stylesInterface: AphroditeInterface,
        stylesTheme: MyTheme,
        direction,
      }}
    >
      <App />
    </WithStylesContext.Provider>
  );
}

To support people using a right-to-left (RTL) context, we recommend using react-with-styles along with react-with-direction. You can provide the direction directly if you have a utility that determines it like in the example above, or you can use the provided utility, WithStylesDirectionAdapter, to grab the direction that's already been set on the react-with-direction context and amend WithStylesContext with it.

import React from 'react';
import WithStylesContext from 'react-with-styles/lib/WithStylesContext';
import WithStylesDirectionAdapter from 'react-with-styles/lib/providers/WithStylesDirectionAdapter';
import AphroditeInterface from 'react-with-styles-interface-aphrodite';
import MyTheme from './MyTheme';

export default function Bootstrap() {
  return (
    <WithStylesContext.Provider
      value={{
        stylesInterface: AphroditeInterface,
        stylesTheme: MyTheme,
      }}
    >
      <WithStylesDirectionAdapter>
        <App />
      </WithStylesDirectionAdapter>
    </WithStylesContext.Provider>
  );
}

Or simply wrap the Bootstrap function above in withDirection yourself.

☝️ Note on performance: Changing the theme many times will cause components to recalculate their styles. Avoid recalculating styles by providing one theme at the highest possible level of your app.

Option 2: Using the ThemedStyleSheet (legacy)

The legacy singleton-based API (using ThemedStyleSheet) is still supported, so you can still use it to register the theme and interface. You do not have to do this if you use the WithStylesContext.Provider. Keep in mind that this API will be deprecated in the next major version of react-with-styles. You can set this up in your own withStyles.js file, like so:

import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';
import AphroditeInterface from 'react-with-styles-interface-aphrodite';
import { withStyles } from 'react-with-styles';

import MyTheme from './MyTheme';

ThemedStyleSheet.registerTheme(MyTheme);
ThemedStyleSheet.registerInterface(AphroditeInterface);

export { withStyles, ThemedStyleSheet };

It is convenient to pass through withStyles from react-with-styles here so that everywhere you use them you can be assured that the theme and interface have been registered. You could likely also set this up as an initializer that is added to the top of your bundles and then use react-with-styles directly in your components.

✋ Because the ThemedStyleSheet implementation stores the theme and interface in variables outside of the React tree, we do not recommended it. This approach does not parallelize, especially if your build systems or apps require rendering with multiple themes.

Step 4. Styling your components

In your components, use withStyles() to define styles. This HOC will inject the right props to consume them through the CSS-in-JS implementation you chose.

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, withStylesPropTypes } from './withStyles';

const propTypes = {
  ...withStylesPropTypes,
};

function MyComponent({ styles, css }) {
  return (
    <div>
      <a
        href="/somewhere"
        {...css(styles.firstLink)}
      >
        A link to somewhere
      </a>

      {' '}
      and
      {' '}

      <a
        href="/somewhere-else"
        {...css(styles.secondLink)}
      >
        a link to somewhere else
      </a>
    </div>
  );
}

MyComponent.propTypes = propTypes;

export default withStyles(({ color }) => ({
  firstLink: {
    color: color.primary,
  },

  secondLink: {
    color: color.secondary,
  },
}))(MyComponent);

You can also use the useStyles hook or a decorator.


Documentation

withStyles([ stylesThunk [, options ] ])

This is a higher-order function that returns a higher-order component used to wrap React components to add styles using the theme. We use this to make themed styles easier to work with.

stylesThunk will receive the theme as an argument, and it should return an object containing the styles for the component.

The wrapped component will receive the following props:

  1. styles - Object containing the processed styles for this component. It corresponds to evaluating stylesInterface.create(stylesThunk(theme)) (or their directional counterparts).
  2. css - Function to produce props to set the styles with on an element. It corresponds to stylesInterface.resolve (or their directional counterparts).
  3. theme - This is the theme object that was registered. You can use it during render as needed, say for inline styles.

Example usage

You can use withStyles() as an HOC:

import React from 'react';
import { withStyles } from './withStyles';

function MyComponent({ css, styles }) {
  return (
    <div {...css(styles.container)}>
      Try to be a rainbow in someone's cloud.
    </div>
  );
}

export default withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}))(MyComponent);

As a decorator:

import React from 'react';
import { withStyles } from './withStyles';

@withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}))
export default function MyComponent({ styles, css }) {
  return (
    <div {...css(styles.container)}>
      Try to be a rainbow in someone's cloud.
    </div>
  );
}

You can also use the experimental hook:

import React from 'react';
import useStyles from 'react-with-styles/lib/hooks/useStyles';

function stylesFn({ color, unit }) {
  return ({
    container: {
      color: color.primary,
      marginBottom: 2 * unit,
    },
  });
}

export default function MyComponent() {
  const { css, styles } = useStyles({ stylesFn });
  return (
    <div {...css(styles.container)}>
      Try to be a rainbow in someone's cloud.
    </div>
  );
}

Options

pureComponent (default: false)

By default withStyles() will create a functional component. If you want to apply the rendering optimizations offered by React.memo, you can set the pureComponent option to true to create a pure functional component instead.

If using the withStyles utility that is found in lib/deprecated/withStyles, it will instead use a React.PureComponent rather than a React.Component. Note that this has a React version requirement of 15.3.0+.

stylesPropName (default: 'styles')

By default, withStyles() will pass down the styles to the wrapped component in the styles prop, but the name of this prop can be customized by setting the stylesPropName option. This is useful if you already have a prop called styles and aren't able to change it.

import React from 'react';
import { withStyles, withStylesPropTypes } from './withStyles';

function MyComponent({ withStylesStyles, css }) {
  return (
    <div {...css(withStylesStyles.container)}>
      Try to be a rainbow in someone's cloud.
    </div>
  );
}

MyComponent.propTypes = {
  ...withStylesPropTypes,
};

export default withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}), { stylesPropName: 'withStylesStyles' })(MyComponent);
cssPropName (default 'css')

The css prop name can also be customized by setting the cssPropName option.

import React from 'react';
import { withStyles, withStylesPropTypes } from './withStyles';

function MyComponent({ withStylesCss, styles }) {
  return (
    <div {...withStylesCss(styles.container)}>
      Try to be a rainbow in someone's cloud.
    </div>
  );
}

MyComponent.propTypes = {
  ...withStylesPropTypes,
};

export default withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}), { cssPropName: 'withStylesCss' })(MyComponent);
themePropName (default 'theme')

The theme prop name can also be customized by setting the themePropName option.

import React from 'react';
import { withStyles, withStylesPropTypes } from './withStyles';

function MyComponent({ css, styles, withStylesTheme }) {
  return (
    <div {...css(styles.container)}>
      <Background color={withStylesTheme.color.primary}>
        Try to be a rainbow in someone's cloud.
      </Background>
    </div>
  );
}

MyComponent.propTypes = {
  ...withStylesPropTypes,
};

export default withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}), { themePropName: 'withStylesTheme' })(MyComponent);
flushBefore (default: false)

Some components depend on previous styles to be ready in the component tree when mounting (e.g. dimension calculations). Some interfaces add styles to the page asynchronously, which is an obstacle for this. So, we provide the option of flushing the buffered styles before the rendering cycle begins. It is up to the interface to define what this means.

css(...styles)

This function takes styles that were processed by withStyles(), plain objects, or arrays of these things. It returns an object with attributes that must be spread into a JSX element. We recommend not inspecting the results and spreading them directly onto the element. In other words className and style props must not be used on the same elements as css().

import React from 'react';
import { withStyles, withStylesPropTypes } from './withStyles';

const propTypes = {
  ...withStylesPropTypes,
};

function MyComponent({ css, styles, bold, padding, }) {
  return (
    <div {...css(styles.container, { padding })}>
      Try to be a rainbow in{' '}
      <a
        href="/somewhere"
        {...css(styles.link, bold && styles.link_bold)}
      >
        someone's cloud
      </a>
    </div>
  );
}

MyComponent.propTypes = propTypes;

export default withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },

  link: {
    color: color.secondary,
  },

  link_bold: {
    fontWeight: 700,
  },
}))(MyComponent);

Accessing your wrapped component with a ref

React 16.3 introduced the ability to pass along refs with the React.forwardRef helper, allowing you to write code like this.

const MyComponent = React.forwardRef(
  function MyComponent({ css, styles }, forwardedRef) {
    return (
      <div {...css(styles.container)} ref={forwardedRef}>
        Hello, World
      </div>
    );
  }
);

Refs will not get passed through HOCs by default because ref is not a prop. If you add a ref to an HOC, the ref will refer to the outermost container component, which is usually not desired. withStyles is set up to pass along your ref to the wrapped component.

const MyComponentWithStyles = withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },
}))(MyComponent);

// the ref will be passed down to MyComponent, which is then attached to the div
const ref = React.createRef()
<MyComponentWithStyles ref={ref} />

ThemedStyleSheet (legacy)

Registers themes and interfaces.

⚠️ Deprecation Warning: ThemedStyleSheet is going to be deprecated in the next major version. Please migrate your applications to use WithStylesContext to provide the theme and interface to use along with withStyles or useStyles. In the meantime, you should be able to use both inside your app for a smooth migration. If this is not the case, please file an issue so we can help.

ThemedStyleSheet.registerTheme(theme) (legacy)

Registers the theme. theme is an object with properties that you want to be made available when styling your components.

import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';

ThemedStyleSheet.registerTheme({
  color: {
    primary: '#FF5A5F',
    secondary: '#00A699',
  },
});

ThemedStyleSheet.registerInterface(interface) (legacy)

Instructs react-with-styles how to process your styles.

import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';
import AphroditeInterface from 'react-with-styles-interface-aphrodite';

ThemedStyleSheet.registerInterface(AphroditeInterface);

Other Examples

With React Router's Link

React Router's <Link/> and <IndexLink/> components accept activeClassName='...' and activeStyle={{...}} as props. As previously stated, css(...styles) must spread to JSX, so simply passing styles.thing or even css(styles.thing) directly will not work. In order to mimic activeClassName/activeStyles you can use React Router's withRouter() Higher Order Component to pass router as prop to your component and toggle styles based on router.isActive(pathOrLoc, indexOnly). This works because <Link /> passes down the generated className from css(..styles) down through to the final leaf.

import React from 'react';
import { withRouter, Link } from 'react-router';
import { css, withStyles } from '../withStyles';

function Nav({ router, styles }) {
  return (
    <div {...css(styles.container)}>
      <Link
        to="/"
        {...css(styles.link, router.isActive('/', true) && styles.link_bold)}
      >
        home
      </Link>
      <Link
        to="/somewhere"
        {...css(styles.link, router.isActive('/somewhere', true) && styles.link_bold)}
      >
        somewhere
      </Link>
    </div>
  );
}

export default withRouter(withStyles(({ color, unit }) => ({
  container: {
    color: color.primary,
    marginBottom: 2 * unit,
  },

  link: {
    color: color.primary,
  },

  link_bold: {
    fontWeight: 700,
  }
}))(Nav));

In the wild

Organizations and projects using react-with-styles.

More Repositories

1

javascript

JavaScript Style Guide
JavaScript
145,177
star
2

lottie-android

Render After Effects animations natively on Android and iOS, Web, and React Native
Java
35,010
star
3

lottie-web

Render After Effects animations natively on Web, Android and iOS, and React Native. http://airbnb.io/lottie/
JavaScript
30,535
star
4

lottie-ios

An iOS library to natively render After Effects vector animations
Swift
25,760
star
5

visx

🐯 visx | visualization components
TypeScript
19,315
star
6

react-sketchapp

render React components to Sketch ⚛️💎
TypeScript
14,939
star
7

react-dates

An easily internationalizable, mobile-friendly datepicker library for the web
JavaScript
11,630
star
8

epoxy

Epoxy is an Android library for building complex screens in a RecyclerView
Java
8,517
star
9

css

A mostly reasonable approach to CSS and Sass.
6,937
star
10

mavericks

Mavericks: Android on Autopilot
Kotlin
5,829
star
11

hypernova

A service for server-side rendering your JavaScript views
JavaScript
5,821
star
12

knowledge-repo

A next-generation curated knowledge sharing platform for data scientists and other technical professions.
Python
5,478
star
13

ts-migrate

A tool to help migrate JavaScript code quickly and conveniently to TypeScript
TypeScript
5,405
star
14

aerosolve

A machine learning package built for humans.
Scala
4,795
star
15

lottie

Lottie documentation for http://airbnb.io/lottie.
HTML
4,457
star
16

DeepLinkDispatch

A simple, annotation-based library for making deep link handling better on Android
Java
4,380
star
17

ruby

Ruby Style Guide
Ruby
3,711
star
18

polyglot.js

Give your JavaScript the ability to speak many languages.
JavaScript
3,706
star
19

MagazineLayout

A collection view layout capable of laying out views in vertically scrolling grids and lists.
Swift
3,296
star
20

native-navigation

Native navigation library for React Native applications
Java
3,128
star
21

streamalert

StreamAlert is a serverless, realtime data analysis framework which empowers you to ingest, analyze, and alert on data from any environment, using datasources and alerting logic you define.
Python
2,847
star
22

infinity

UITableViews for the web (DEPRECATED)
JavaScript
2,802
star
23

HorizonCalendar

A declarative, performant, iOS calendar UI component that supports use cases ranging from simple date pickers all the way up to fully-featured calendar apps.
Swift
2,772
star
24

airpal

Web UI for PrestoDB.
Java
2,757
star
25

swift

Airbnb's Swift Style Guide
Markdown
2,407
star
26

Showkase

🔦 Showkase is an annotation-processor based Android library that helps you organize, discover, search and visualize Jetpack Compose UI elements
Kotlin
2,093
star
27

synapse

A transparent service discovery framework for connecting an SOA
Ruby
2,072
star
28

paris

Define and apply styles to Android views programmatically
Kotlin
1,907
star
29

AirMapView

A view abstraction to provide a map user interface with various underlying map providers
Java
1,870
star
30

rheostat

Rheostat is a www, mobile, and accessible slider component built with React
JavaScript
1,692
star
31

binaryalert

BinaryAlert: Serverless, Real-time & Retroactive Malware Detection.
Python
1,405
star
32

epoxy-ios

Epoxy is a suite of declarative UI APIs for building UIKit applications in Swift
Swift
1,201
star
33

nerve

A service registration daemon that performs health checks; companion to airbnb/synapse
Ruby
942
star
34

okreplay

📼 Record and replay OkHttp network interaction in your tests.
Groovy
782
star
35

chronon

Chronon is a data platform for serving for AI/ML applications.
Scala
731
star
36

RxGroups

Easily group RxJava Observables together and tie them to your Android Activity lifecycle
Java
694
star
37

react-outside-click-handler

OutsideClickHandler component for React.
JavaScript
612
star
38

ResilientDecoding

This package makes your Decodable types resilient to decoding errors and allows you to inspect those errors.
Swift
595
star
39

babel-plugin-dynamic-import-node

Babel plugin to transpile import() to a deferred require(), for node
JavaScript
575
star
40

kafkat

KafkaT-ool
Ruby
503
star
41

babel-plugin-dynamic-import-webpack

Babel plugin to transpile import() to require.ensure, for Webpack
JavaScript
499
star
42

babel-plugin-inline-react-svg

A babel plugin that optimizes and inlines SVGs for your React Components.
JavaScript
473
star
43

BuckSample

An example app showing how Buck can be used to build a simple iOS app.
Objective-C
461
star
44

lunar

🌗 React toolkit and design language for Airbnb open source and internal projects.
TypeScript
461
star
45

SpinalTap

Change Data Capture (CDC) service
Java
430
star
46

artificial-adversary

🗣️ Tool to generate adversarial text examples and test machine learning models against them
Python
394
star
47

dynein

Airbnb's Open-source Distributed Delayed Job Queueing System
Java
383
star
48

hammerspace

Off-heap large object storage
Ruby
369
star
49

trebuchet

Trebuchet launches features at people
Ruby
312
star
50

reair

ReAir is a collection of easy-to-use tools for replicating tables and partitions between Hive data warehouses.
Java
279
star
51

zonify

a command line tool for generating DNS records from EC2 instances
Ruby
270
star
52

ottr

Serverless Public Key Infrastructure Framework
Python
270
star
53

omniduct

A toolkit providing a uniform interface for connecting to and extracting data from a wide variety of (potentially remote) data stores (including HDFS, Hive, Presto, MySQL, etc).
Python
254
star
54

hypernova-react

React bindings for Hypernova.
JavaScript
248
star
55

smartstack-cookbook

The chef recipes for running and testing Airbnb's SmartStack
Ruby
245
star
56

interferon

Signaling you about infrastructure or application issues
Ruby
239
star
57

babel-preset-airbnb

A babel preset for transforming your JavaScript for Airbnb
JavaScript
227
star
58

backpack

A pack of UI components for Backbone projects. Grab your backpack and enjoy the Views.
HTML
223
star
59

goji-js

React ❤️ Mini Program
TypeScript
218
star
60

react-with-direction

Components to provide and consume RTL or LTR direction in React
JavaScript
191
star
61

stemcell

Airbnb's EC2 instance creation and bootstrapping tool
Ruby
185
star
62

hypernova-ruby

Ruby client for Hypernova.
Ruby
141
star
63

kafka-statsd-metrics2

Send Kafka Metrics to StatsD.
Java
135
star
64

optica

A tool for keeping track of nodes in your infrastructure
Ruby
133
star
65

sparsam

Fast Thrift Bindings for Ruby
C++
124
star
66

js-shims

JS language shims used by Airbnb.
JavaScript
123
star
67

lottie-spm

Swift Package Manager support for Lottie, an iOS library to natively render After Effects vector animations
Ruby
122
star
68

bossbat

Stupid simple distributed job scheduling in node, backed by redis.
JavaScript
118
star
69

nimbus

Centralized CLI for JavaScript and TypeScript developer tools.
TypeScript
118
star
70

browser-shims

Browser and JS shims used by Airbnb.
JavaScript
117
star
71

twitter-commons-sample

A sample REST service based on Twitter Commons
Java
103
star
72

is-touch-device

Is the current JS environment a touch device?
JavaScript
90
star
73

rudolph

A serverless sync server for Santa, built on AWS
Go
79
star
74

hypernova-node

node.js client for Hypernova
JavaScript
73
star
75

plog

Fire-and-forget UDP logging service with custom Netty pipelines & extensive monitoring
Java
72
star
76

react-create-hoc

Create a React Higher-Order Component (HOC) following best practices.
JavaScript
67
star
77

vulnture

Python
67
star
78

cloud-maker

Building castles in the sky
Ruby
67
star
79

deline

An ES6 template tag that strips unwanted newlines from strings.
JavaScript
64
star
80

react-with-styles-interface-react-native

Interface to use react-with-styles with React Native
JavaScript
63
star
81

sputnik

Scala
63
star
82

mocha-wrap

Fluent pluggable interface for easily wrapping `describe` and `it` blocks in Mocha tests.
JavaScript
54
star
83

react-with-styles-interface-aphrodite

Interface to use react-with-styles with Aphrodite
JavaScript
54
star
84

eslint-plugin-react-with-styles

ESLint plugin for react-with-styles
JavaScript
49
star
85

sssp

Software distribution by way of S3 signed URLs
Haskell
47
star
86

alerts

An example alerts repo, for use with airbnb/interferon.
Ruby
46
star
87

apple-tv-auth

Example application to demonstrate how to build Apple TV style authentication.
Ruby
44
star
88

airbnb-spark-thrift

A library for loadling Thrift data into Spark SQL
Scala
42
star
89

jest-wrap

Fluent pluggable interface for easily wrapping `describe` and `it` blocks in Jest tests.
JavaScript
40
star
90

billow

Query AWS data without API credentials. Don't wait for a response.
Java
38
star
91

gosal

A Sal client written in Go
Go
35
star
92

backbone.baseview

DEPRECATED: A simple base view class for Backbone.View
JavaScript
34
star
93

anotherlens

News Deeply X Airbnb.Design - Another Lens
HTML
33
star
94

eslint-plugin-miniprogram

TypeScript
33
star
95

react-component-variations

JavaScript
33
star
96

react-with-styles-interface-css

📃 CSS interface for react-with-styles
JavaScript
32
star
97

transformpy

transformpy is a Python 2/3 module for doing transforms on "streams" of data
Python
29
star
98

appear

reveal terminal programs in the gui
Ruby
29
star
99

puppet-munki

Puppet
28
star
100

pool-hall

JavaScript
26
star