Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!