Reputation: 1265
What is the best way have 3 style types based on props?
Like Bootstrap, aiming to have a default, small, and medium size.
Here I have default and small, but how do I account for a large size too?
const Button = styled.button`
background: teal;
border-radius: 8px;
color: white;
height: ${props => props.small ? 40 : 60}px;
width: ${props => props.small ? 60 : 120}px;
`;
class Application extends React.Component {
render() {
return (
<div>
<Button small>Click Me</Button>
<Button>Click Me</Button>
<Button large>Click Me</Button>
</div>
)
}
}
Upvotes: 1
Views: 4722
Reputation: 47
Harsha Venkatram, here is the typescript version:
import * as Styles from './styles';
interface Props {
size: number; //for example, or string or whatever type is it
variant: 'primary' | 'secondary' | 'tertiary' //etc...
}
const ButtonBase = styled.button<Props>`
${Styles.buttonbase};
${props => Styles[props.size]};
${props => Styles[props.variant]};
`;
Upvotes: 1
Reputation: 1265
I've seen this as a solution too:
const ButtonBase = styled.button`
padding: ${props => {
if (props.xl) return props.theme.buttonSize.xl;
if (props.lg) return props.theme.buttonSize.lg;
if (props.md) return props.theme.buttonSize.md;
if (props.sm) return props.theme.buttonSize.sm;
return props.theme.buttonSize.nm;
}};
`
https://codesandbox.io/s/735ppo790x
Upvotes: 4
Reputation: 14927
Here's an abbreviated example of an option that I use.
/* import separate css file from styles.js */
import * as Styles from './styles';
/* concat styles based on props */
const ButtonBase = styled.button`
${Styles.buttonbase};
${props => Styles[props.size]};
${props => Styles[props.variant]};
`;
const Button = ({ size, variant, ...rest }) => (
<ButtonBase
size={size}
variant={variant}
{...rest}
...
And in the styles file (with the css removed for brevity)
import { css } from 'styled-components';
/* styles common to all buttons */
export const buttonbase = css`...`;
/* theme variants */
export const primary = css`...`;
export const secondary = css`...`;
export const tertiary = css`...`;
/* size variants */
export const small = css`...`;
export const medium = css`...`;
export const large = css`...`;
Upvotes: 4