Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda