Skip to content

Instantly share code, notes, and snippets.

@its-monotype
Last active December 11, 2022 17:47
Show Gist options
  • Save its-monotype/f24b7b4f4d9ea6f6e3d3dc656072c6ee to your computer and use it in GitHub Desktop.
Save its-monotype/f24b7b4f4d9ea6f6e3d3dc656072c6ee to your computer and use it in GitHub Desktop.
withClassName React HOC (with forwardRef)
import React from 'react';
import clsx from 'clsx';
import { getDisplayName, __DEV__ } from '@/utils/helpers';
export type withClassNameProps = {
className?: string;
};
export function withClassName<T, P extends object>(
WrappedComponent: React.ForwardRefExoticComponent<
React.PropsWithoutRef<P & withClassNameProps> & React.RefAttributes<T>
>,
classes?: string,
) {
const WithClassName = React.forwardRef<T, P & withClassNameProps>(
function WithClassName(props, ref) {
const { className, ...rest } = props;
return (
<WrappedComponent
ref={ref}
className={clsx(classes, className)}
{...(rest as React.PropsWithoutRef<P>)}
/>
);
},
);
if (__DEV__) {
WithClassName.displayName = `WithClassName(${getDisplayName(
WrappedComponent,
)})`;
}
return WithClassName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment