Search code examples
reactjsstyled-components

React Styled-Components 3 Button sizes


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>
    )
  }
}

Codepen


Solution

  • 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`...`;