Styled-system: Using theme properties in variants (with typescript)

Created on 29 Nov 2019  路  4Comments  路  Source: styled-system/styled-system

Took me a while to figure this out, I so thought it might be worth documenting :)

import styled, {Theme} from "styled"
import {css, SerializedStyles} from "@emotion/core"
import {variant} from "styled-system"

type Variants = "primary" | "secondary"

type VariantsMap = {[name in Variants]: SerializedStyles}

const variants = (theme: Theme): VariantsMap => ({
  primary: css`
    color: ${theme.colors.white};
    background-color: ${theme.colors.violet};
  `,
  secondary: css`
    color: ${theme.colors.white};
    background-color: ${theme.colors.black};
  `,
})

interface IButtonProps {
  fullWidth?: boolean
  variant?: Variants
}

export const Button = styled.button<IButtonProps>`
  display: block;
  padding: .5rem 2rem;
  border-radius: .5rem;
  font-size: ${(props) => props.theme.fontSizes[18]};
  font-weight: ${(props) => props.theme.fontWeights.bold};

  ${(props) => props.fullWidth && css`
    width: 100%;
  `}

  ${(props) => variant({
    variants: variants(props.theme)
  })}
`

Button.defaultProps = {
  variant: "primary",
}

Most helpful comment

@jacek213 The trick looks like just work with emotion, the css from styled-components generates styles as:

0: color:white;
1: #C73D3D;

For something like this:

import { css } from 'styled-components';
const Button = styled.button`

${({ theme }) =>
    variant({
      variants: {
          warning: css`
             color: white;
              background-color: ${theme.colors.error};
          `,
      }
   })
}`;

All 4 comments

Thanks, but I'm not sure what this issue is intended for. Can you please clarify what this is about?

@jxnblk Well, as I've stated, I think it's worth documenting. Currently the docs don't include a typescript section, so if you're willing to accept a PR I can create one with description of using variants with TS.

This looks like general TypeScript usage, is there anything special you needed to do WRT this library?

@jacek213 The trick looks like just work with emotion, the css from styled-components generates styles as:

0: color:white;
1: #C73D3D;

For something like this:

import { css } from 'styled-components';
const Button = styled.button`

${({ theme }) =>
    variant({
      variants: {
          warning: css`
             color: white;
              background-color: ${theme.colors.error};
          `,
      }
   })
}`;

Was this page helpful?
0 / 5 - 0 ratings

Related issues

benjamingeorge picture benjamingeorge  路  3Comments

gregberge picture gregberge  路  4Comments

vdesdoigts picture vdesdoigts  路  3Comments

fk picture fk  路  3Comments

eMontielG picture eMontielG  路  4Comments