Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created November 12, 2021 14:47
Show Gist options
  • Save karol-majewski/81a3a9ee558901c01fa47f8c2632ba82 to your computer and use it in GitHub Desktop.
Save karol-majewski/81a3a9ee558901c01fa47f8c2632ba82 to your computer and use it in GitHub Desktop.
withProps with support for forwardRef
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