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

150
Views
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 answers
Answer question

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 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!