Last active
December 11, 2022 17:47
-
-
Save its-monotype/f24b7b4f4d9ea6f6e3d3dc656072c6ee to your computer and use it in GitHub Desktop.
withClassName React HOC (with forwardRef)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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