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

253
Visualizações
How to add custom (or outdated) attributes to styled-components?

I'm developing tool for making newsletters. That means I need to use lots of outdated HTML4/XHTML1 tags and attrs. For example, I want to create an element like this:

<table align="center" cellpadding="0" cellspacing="0" border="0" width="100%" style="%some css here%">
...
</table>

My stack is React 17, styled-components v5.3.3 and typescript v4.5.5.

Styled components definition:

interface ITable {
  align?: string,
  cellPadding?: number,
  cellSpacing?: number,
  border?: number,
  width?: string,
}

export const SCTable = styled.table.attrs(({ cellPadding = 0, cellSpacing = 0, border = 0, align, width }: ITable) => {
  return {
    cellPadding,
    cellSpacing,
    align,
    width,
    border,
  }
})<ITable>`
`;

Usage:

<SCTable width="42%" align="center"></SCTable>

Result:

<table width="42%" cellpadding="0" cellspacing="0" class="..."></table>

As you can see only 3 of 5 attrs were added. I've checked React docs about this and React doesn't support align and border attrs, but at the same time

You may also use custom attributes as long as they’re fully lowercase.

Also there are some issues with table tag in HTML5, because border attr is deprecated (but align is only not supported, as cellPadding). Switching doctype to XHTML have no effect.

Any thoughts how to make all attrs to appear in element? Replacing them with CSS won't help in case of opening result markup in some email clients.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Ok, I found the solution. Outdated props were filtered by styled-components, and you can override this filter with shouldForwardProp:

const SCTable = styled.table
  .withConfig({
    shouldForwardProp: (prop, defaultValidatorFn) => ['align', 'border'].includes(prop) || defaultValidatorFn(prop),
  })
  .attrs<ITable>(({ cellPadding = 0, cellSpacing = 0, border = 0, align, width }) => {
    return {
      cellPadding,
      cellSpacing,
      align,
      width,
      border,
    };
  })<ITable>``;
about 4 years ago · Juan Pablo Isaza 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