typescript-styled-is v2.1.0
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'))`
color: green;
`}
`
<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 falsesome(...props: string[])
returns css when one of props is truesomeNot(...props: string[])
returns css when one of props is false