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

152
Visualizações
How to pass the className prop to all components by default without defining it every time

I have an issue with code duplication when creating any new component.

How I can pass className between all components without defining the className prop every time I create a new component?

Let's say I created a new component called ChildComponent, I should define the className and add a default value for it, and every time I create a new component I define the className again.

type ChildComponentProps = {
  className?: string;
  children: string;
};

export default function ChildComponent({ className, children }: ChildComponentProps): JSX.Element {
  return <p className={className ?? ''}>{children}</p>;
}

ChildComponent.defaultProps = {
  className: null,
};

So. is there any way to pass the className between components without code duplication in every component?

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

0

Expanding upon what Julio Alves wrote in their comment, you can create a types/foo.d.ts file with the following contents:

type CustomComponentType = React.FC<{
  className?: string;
}>;

Then in your code you can directly reference your CustomComponentType without importing it:

const ChildComponent: CustomComponentType = ({ className, children }) => (
  <p className={className}>{children}</p>
);

export default ChildComponent;

And, there is no need to define defaultProps, at least in this case.

If you are facing similar issues with other standard props too, then instead of writing each one in the declaration file, you can use the types provided by React (technically DefinitelyTyped):

const MyParagraphWrapper: React.FC<React.HTMLProps<HTMLParagraphElement>> = ({
  children,
  ...props
}) => <p {...props}>{children}</p>; // eslint-disable-line react/jsx-props-no-spreading

You can pass any/unknown if you wish to generalize this.

type GeneralWrapperComponentType = React.FC<React.HTMLProps<unknown>>;
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