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?
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>>;