Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda