Skip to content

Instantly share code, notes, and snippets.

@AlexcastroDev
Last active March 10, 2023 15:13
Show Gist options
  • Save AlexcastroDev/aaa999c6a66565bd7dd5338e98ddd9c8 to your computer and use it in GitHub Desktop.
Save AlexcastroDev/aaa999c6a66565bd7dd5338e98ddd9c8 to your computer and use it in GitHub Desktop.
React Decorator as High order component without class
import React from 'react'
import { IAsyncAppDispatch } from 'my-package'
export interface IHandlers {
onSuccess: IAsyncAppDispatch['onSuccess']
onError: IAsyncAppDispatch['onError']
}
export interface DefaultFormProps {
handlers?: IHandlers
}
export interface IDefaultHeaderProps {
header?: {
onClose?: () => void
loading?: boolean
}
}
export interface IModuleFormDecoratorProps {
wrapper: React.FC<React.PropsWithChildren<IHandlers>>
}
function notImplementedHandler() {
console.info('[form]: method not implemented')
}
/**
* @param WrappedComponent
* @param options
* @returns The ModuleFormDecorator function
* returns a new component with default onSuccess and onError handlers.
* The type of the returned component is the same as the type of WrappedComponent.
*/
function ModuleFormDecorator<P>(
EnhancedComponent: React.ComponentType<P>,
options: IModuleFormDecoratorProps
) {
const { wrapper: WrapperComponent } = options
const ModuleFormWrapper: React.FC<P & DefaultFormProps> = (props) => {
const onSuccess = props?.handlers?.onSuccess || notImplementedHandler
const onError = props?.handlers?.onError || notImplementedHandler
return (
<WrapperComponent onSuccess={onSuccess} onError={onError}>
<EnhancedComponent {...props} />
</WrapperComponent>
)
}
return React.memo(ModuleFormWrapper)
}
/**
* ModuleFormDecorator is a higher-order function that
* takes a component as input and returns a
* new component that enhances the input component
* with default onSuccess and onError handlers.
*/
export default ModuleFormDecorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment