Search code examples
javascriptreactjsstyled-componentsprettier

Multiple evaluations in template literal... How can I improve my padding calculation for styled-components?


I'm trying to use styled components to style a button with some padding as shown below. Is there a cleaner way of returning two values using a single expression so I can clean this up?

export const Button = styled.button`
  padding: ${props => (props.primary ? rhythm(0.65) : rhythm(0.5))} ${props => (props.primary ? rhythm(1.6) : rhythm(1))};
`



Additionally, Prettier formats the previous code as follows. This is not valid css and so does not work. Is this a bug in prettier or is my code just horrible?

Broken:

export const Button = styled.button`
  padding: ${props => (props.primary ? rhythm(0.65) : rhythm(0.5))}
    ${props => (props.primary ? rhythm(1.6) : rhythm(1))};
`

Solution

  • You can generate both values with one template string. It would be more readable to create a simple function, that generates the string:

    const rhythm = v => `${v}em`; // mock
    
    const getPadding = (a, b) => `${rhythm(a)} ${rhythm(b)}`
    
    const Button = styled.button`
      padding: ${props => (props.primary ? getPadding(0.65, 1.6) : getPadding(0.5, 1))};
    `
    
    ReactDOM.render(
      <div>
        <Button primary>Primary</Button>
        <Button>Not primary</Button>
      </div>,
      root
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.0/styled-components.js"></script>
    
    <div id="root"></div>