Created
November 12, 2021 14:47
-
-
Save karol-majewski/81a3a9ee558901c01fa47f8c2632ba82 to your computer and use it in GitHub Desktop.
withProps with support for forwardRef
This file contains 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 * as React from 'react'; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export function withProps<C extends React.ComponentType<any>, D extends Partial<React.ComponentPropsWithoutRef<C>> & JSX.IntrinsicAttributes>( | |
Component: C, | |
defaults: D | |
): React.ForwardRefExoticComponent<React.PropsWithoutRef<Omit<React.ComponentProps<C>, keyof D>> & React.RefAttributes<React.ElementRef<C>>> { | |
const renderFunction: React.ForwardRefRenderFunction<React.ElementRef<C>, Omit<React.ComponentProps<C>, keyof D>> = (props, ref) => { | |
return React.createElement(Component, { ...props, defaults, ref }); | |
}; | |
renderFunction.displayName = `withProps(${Component.displayName || Component.name})`; | |
return React.forwardRef(renderFunction); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment