• Stars
    star
    802
  • Rank 56,815 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated about 2 years ago

Reviews

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

Repository Details

Useful interpolated functions for CSS-in-JS

styled-tools 💅

NPM version NPM downloads Dependencies Build Status Coverage Status

Useful interpolated functions for styled-components 💅, emotion 👩‍🎤, JSS and other CSS-in-JS libraries.

Install

npm:

npm i styled-tools

Yarn:

yarn add styled-tools

Usage

import styled, { css } from "styled-components";
import { prop, ifProp, switchProp } from "styled-tools";

const Button = styled.button`
  color: ${prop("color", "red")};
  font-size: ${ifProp({ size: "large" }, "20px", "14px")};
  background-color: ${switchProp("theme", {
    dark: "blue", 
    darker: "mediumblue", 
    darkest: "darkblue" 
  })};
`;

// renders with color: blue
<Button color="blue" />

// renders with color: red
<Button />

// renders with font-size: 20px
<Button size="large" />

// renders with background-color: mediumblue
<Button theme="darker" />

A more complex example:

const Button = styled.button`
  color: ${prop("theme.colors.white", "#fff")};
  font-size: ${ifProp({ size: "large" }, prop("theme.sizes.lg", "20px"), prop("theme.sizes.md", "14px"))};
  background-color: ${prop("theme.colors.black", "#000")};
  
  ${switchProp("kind", {
    dark: css`
      background-color: ${prop("theme.colors.blue", "blue")};
      border: 1px solid ${prop("theme.colors.blue", "blue")};
    `,
    darker: css`
      background-color: ${prop("theme.colors.mediumblue", "mediumblue")};
      border: 1px solid ${prop("theme.colors.mediumblue", "mediumblue")};
    `,
    darkest: css`
      background-color: ${prop("theme.colors.darkblue", "darkblue")};
      border: 1px solid ${prop("theme.colors.darkblue", "darkblue")};
    `
  })}
  
  ${ifProp("disabled", css`
    background-color: ${prop("theme.colors.gray", "#999")};
    border-color: ${prop("theme.colors.gray", "#999")};
    pointer-events: none;
  `)}
`;

API

Table of Contents

prop

Returns the value of props[path] or defaultValue

Parameters

  • path string
  • defaultValue any

Examples

import styled from "styled-components";
import { prop } from "styled-tools";

const Button = styled.button`
  color: ${prop("color", "red")};
`;

Returns PropsFn

theme

Same as prop, except that it returns props.theme[path] instead of props[path].

Parameters

  • path string
  • defaultValue any

Examples

import styled from "styled-components";
import { theme } from "styled-tools";

const Button = styled.button`
 color: ${theme("button.color", "red")};
`;

palette

Returns props.theme.palette[key || props.palette][tone || props.tone || 0] or defaultValue.

Parameters

  • keyOrTone (string | number)
  • toneOrDefaultValue any
  • defaultValue any

Examples

import styled, { ThemeProvider } from "styled-components";
import { palette } from "styled-tools";

const theme = {
  palette: {
    primary: ['#1976d2', '#2196f3', '#71bcf7', '#c2e2fb'],
    secondary: ['#c2185b', '#e91e63', '#f06292', '#f8bbd0']
  }
};

const Button = styled.button`
  color: ${palette(1)};                    // props.theme.palette[props.palette][1]
  color: ${palette("primary", 1)};         // props.theme.palette.primary[1]
  color: ${palette("primary")};            // props.theme.palette.primary[props.tone || 0]
  color: ${palette("primary", -1)};        // props.theme.palette.primary[3]
  color: ${palette("primary", 10)};        // props.theme.palette.primary[3]
  color: ${palette("primary", -10)};       // props.theme.palette.primary[0]
  color: ${palette("primary", 0, "red")};  // props.theme.palette.primary[0] || red
`;

<ThemeProvider theme={theme}>
  <Button palette="secondary" />
</ThemeProvider>

ifProp

Returns pass if prop is truthy. Otherwise returns fail

Parameters

Examples

import styled from "styled-components";
import { ifProp, palette } from "styled-tools";

const Button = styled.button`
  background-color: ${ifProp("transparent", "transparent", palette(0))};
  color: ${ifProp(["transparent", "accent"], palette("secondary"))};
  font-size: ${ifProp({ size: "large" }, "20px", ifProp({ size: "medium" }, "16px", "12px"))};
`;

Returns PropsFn

ifNotProp

Returns pass if prop is falsy. Otherwise returns fail

Parameters

Examples

import styled from "styled-components";
import { ifNotProp } from "styled-tools";

const Button = styled.button`
  font-size: ${ifNotProp("large", "20px", "30px")};
`;

Returns PropsFn

withProp

Calls a function passing properties values as arguments.

Parameters

Examples

// example with polished
import styled from "styled-components";
import { darken } from "polished";
import { withProp, prop } from "styled-tools";

const Button = styled.button`
  border-color: ${withProp(prop("theme.primaryColor", "blue"), darken(0.5))};
  font-size: ${withProp("theme.size", size => `${size + 1}px`)};
  background: ${withProp(["foo", "bar"], (foo, bar) => `${foo}${bar}`)};
`;

Returns PropsFn

switchProp

Switches on a given prop. Returns the value or function for a given prop value. Third parameter is default value.

Parameters

Examples

import styled, { css } from "styled-components";
import { switchProp, prop } from "styled-tools";

const Button = styled.button`
  font-size: ${switchProp(prop("size", "medium"), {
    small: prop("theme.sizes.sm", "12px"),
    medium: prop("theme.sizes.md", "16px"),
    large: prop("theme.sizes.lg", "20px")
  }, prop("theme.sizes.md", "16px"))};
  ${switchProp("theme.kind", {
    light: css`
      color: LightBlue;
    `,
    dark: css`
      color: DarkBlue;
    `
  }, css`color: black;`)}
`;

<Button size="large" theme={{ kind: "light" }} />

Returns PropsFn

Types

Needle

A Needle is used to map the props to a value. This can either be done with a path string "theme.size.sm" or with a function (props) => props.theme.size.sm (these two examples are equivalent).

All of styled-tools can be used as Needles making it possible to do composition between functions. ie ifProp(theme("dark"), "black", "white")

Type: (string | Function)

License

MIT © Diego Haz

More Repositories

1

constate

React Context + State
TypeScript
3,924
star
2

arc

React starter kit based on Atomic Design
JavaScript
2,914
star
3

rest

REST API generator with Node.js, Express and Mongoose
JavaScript
1,788
star
4

generact

Generate React components by replicating your own
JavaScript
1,482
star
5

awesome-react-context

😎 A curated list of stuff related to the new React Context API
JavaScript
917
star
6

schm

Composable schemas for JavaScript and Node.js
JavaScript
513
star
7

reuse

♻️ Reuse React components to create new ones
TypeScript
495
star
8

singel

Single Element Pattern
JavaScript
408
star
9

nod

Node.js module generator/boilerplate with Babel, Jest, Flow, Documentation and more
JavaScript
360
star
10

redux-saga-thunk

Dispatching an action handled by redux-saga returns promise
JavaScript
221
star
11

styled-theme

Extensible theming system for styled-components 💅
JavaScript
182
star
12

querymen

Querystring parser middleware for MongoDB, Express and Nodejs (MEN)
JavaScript
129
star
13

parse-prop-types

Parses React prop-types into a readable object
JavaScript
69
star
14

bodymen

Body parser middleware for MongoDB, Express and Nodejs (MEN)
JavaScript
47
star
15

list-react-files

List React component files inside a directory
JavaScript
25
star
16

redux-saga-social-login

Facebook/Google login implementation with redux-saga
JavaScript
25
star
17

mongoose-keywords

Mongoose plugin that generates a keywords path combining other paths values
JavaScript
22
star
18

redux-modules

A modular approach to better organize redux stuff (not another library)
JavaScript
21
star
19

coolors-to-hex

Get hexadecimal values from a coolors url
JavaScript
18
star
20

generator-rest-example

A fully commented RESTful API example generated with generator-rest
JavaScript
18
star
21

styled-selector

Get static CSS(-in-JS) selectors from React components
TypeScript
17
star
22

webpack-blocks-split-vendor

A webpack block that splits vendor javascript into separated bundle
JavaScript
15
star
23

webpack-blocks-happypack

A webpack block that adds happypack support to your webpack config
JavaScript
12
star
24

redux-form-submit

Adds an async submit action creator to redux-form
JavaScript
9
star
25

webpack-spawn-plugin

A webpack plugin that runs child_process.spawn within compilation
JavaScript
7
star
26

waterfall-grid

A Polymer wrapper element for waterfall.js, a 1KB Javascript library for Pinterest-like grids.
HTML
7
star
27

webpack-blocks-server-source-map

A webpack block that adds source map support to server bundle
JavaScript
5
star
28

yo

A Yeoman generator for generating next generation of Yeoman generators
JavaScript
5
star
29

webpack-assets-by-type-plugin

A webpack plugin that save assets by type
JavaScript
5
star
30

arc-universal-redux

Universal Redux version of ARc boilerplate
JavaScript
5
star
31

webpack-sort-chunks

Sorts webpack chunks by dependency
JavaScript
4
star
32

webpack-child-config-plugin

A webpack plugin that runs/watches another config
JavaScript
4
star
33

rest-api

REST API Boilerplate with Mongoose, Express and Nodejs
JavaScript
4
star
34

rich-param

An object with name and value which accepts pluggable methods as formatters or validators
JavaScript
3
star
35

reakit-code-lab

TypeScript
3
star
36

arc-fullstack

Fullstack version of ARc boilerplate
JavaScript
3
star
37

is-git-rev

Verify if a string is a git-rev hash
JavaScript
3
star
38

mongoose-create-unique

Mongoose plugin to create a document or return the existing one based on the unique index
JavaScript
3
star
39

divisa

A game about war and peace.
JavaScript
2
star
40

eyeport

Collection of useful methods to deal with element and viewports in DOM
JavaScript
2
star
41

alpha-bank

JavaScript
2
star
42

guild

Just a social network prototype made with jQuery
HTML
2
star
43

adjacente

Blog para disciplina Expansão dos Sentidos
JavaScript
1
star
44

radiotoca

A PHP web radio with Twitter integration
PHP
1
star
45

clone

JavaScript
1
star
46

diegohaz

1
star
47

hear-parse

JavaScript
1
star
48

hear-api

JavaScript
1
star
49

diegohaz.com

JavaScript
1
star