user17711104
user17711104

Reputation:

Understanding css helper function in styled components

Styled components has a helper css function. But I don't understand when should I used it.

For example this is their example where they use it:

import styled, { css } from 'styled-components'

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`

const StyledComp = styled.div`
  /* This is an example of a nested interpolation */
  ${props => (props.complex ? complexMixin : 'color: blue;')};
`

But if we take similar example from docs here they don't use it:

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

Their description is also not clear and is confusing me:

A helper function to generate CSS from a template literal with interpolations. You need to use this if you return a template literal with functions inside an interpolation due to how tagged template literals work in JavaScript.

Can someone help explain why we need it?

PS this answer also doesn't use it

Upvotes: 12

Views: 4168

Answers (1)

CasperCarver
CasperCarver

Reputation: 74

I use the css function when I create variants for a component:

that is variant switcher:

const sizeVariant: Record<NonNullable<StyledLogoProps['size']>, ReturnType<typeof css>> = {
  small: css`
    width: 44px;
    height: 44px;
  `,
  regular: css`
    width: 93px;
    height: 93px;
  `,
};

that is component was created by 'styled-components':

interface StyledLogoProps {
  size: 'small' | 'regular';
}

export const StyledLogo = styled.div<StyledLogoProps>`
  ${({ size }) => sizeVariant[size]}
`;

and this is the use in the react:

<>
  <StyledLogo size="regular" />
  <StyledLogo size="small" />
</>

quite a useful thing

Upvotes: 3

Related Questions