Search code examples
cssreactjsjsxstyled-components

How to concatenate jsx in styled components


I have trouble adding padding to a component. This is the current code (it works fine)

padding: ${props =>
  props.isMobile && props.variant === "a"
    ? Spacing.Large
    : Spacing.Small};

However I want the padding to only be top and bottom and the side to be 0, so I want to do something like this: (notice the 0's)

padding: ${props =>
  props.isMobile && props.variant === "a"
    ? 0 Spacing.Large
    : 0 Spacing.Small};

But it will give me a syntax error, what is the correct way to handle this?


Solution

  • padding takes a string value, so when you do the ternary statement, you need to make sure it's a string.

    padding: ${props =>
      props.isMobile && props.variant === "a"
        ? `0 ${Spacing.Large}`
        : `0 ${Spacing.Small}`};
    

    This will make sure the ternary is properly executed.