typescript-styled-is
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published
typescript-styled-is
Flag utility for styled-components inspired with styled-is created by yldio. I missed support for TypeScript so I wrote my own package from scratch.



The purpose is to simplify writing and improve reading of conditional statements in styled-components. With this package it's possible to create advanced components (e.g. <Button /> with different styles like primary, secondary) in one component without hussle.

Installation

To use typescript-styled-is there is required another package - styled-components. Otherwise package has no sense in your project. Depends of your package manager, you can use yarn or npm.

yarn add typescript-styled-is
npm install typescript-styled-is

Usage

Package styled-components allows to conditional statements for CSS by comparing props' values.

import styled from 'styled-components'
 
const Button = styled.button`
  color: ${props => props.active ? 'active' : 'green'};
`

That syntax is not readable and nested conditions are even harder to read. typescript-styled-is allows to easily write conditions.

import styled from 'styled-components'
import is, { isNot, some, someNot } from 'typescript-styled-is'
 
const Button = styled.button`
  color: 'red';
 
  ${is('active')`
    color: 'green';
  `}
 
  ${isNot('primary', 'secondary')`
    color: 'blue';
  `}
 
  ${some('used', 'disabled', 'inactive')`
    color: 'violet';
  `}
  
  ${someNot('used', 'disabled', 'inactive')`
    color: 'violet';
  `}
`
 
<Button />
<Button active={true} primary={true} />
<Button used={true} />

This utility does not provide any tools to remove unused styles. Style color: red will be there always. So if your component is active, your styles will contain two declarations for color.

For more complicated scenarios, since version 2.0 it is possible to nest conditions, e.g.:

import styled from 'styled-components'
import is, { isNot } from 'typescript-styled-is'
 
const Button = styled.button`
  color: red;
  ${is('primary, isNot('secondary'))`
    colorgreen;
  `}
`
 
<Button primary={true} />
<Button primary={true} secondary={false} />

API

  • is(...props: string[]) returns css when all props are true (default export)
  • isNot(...props: string[]) return css when all props are false
  • some(...props: string[]) returns css when one of props is true
  • someNot(...props: string[]) returns css when one of props is false

Package Sidebar

Install

npm i typescript-styled-is

Weekly Downloads

119

Version

2.1.0

License

MPL-2.0

Unpacked Size

26.6 kB

Total Files

7

Last publish

Collaborators

  • grzgajda