redux-dynamic-modules
redux-dynamic-modules copied to clipboard
Suggestion for React HOC Wrapper for DynamicModuleLoader
There may be many folks, including myself, that prefer the "withSomeFeature" HOC style for initiating a Redux module load. To that end, have provided some working code below.
I am posting here instead of submitting, as I don't know if there is a better way to achieve this or not... but feel free to use the code as-is
// withReduxDynamicModule.tsx
import React from 'react';
import { IModuleTuple } from 'redux-dynamic-modules-react';
import { DynamicModuleLoader } from './DynamicModuleLoader';
const withReduxDynamicModule = <P extends object>(dynamicReduxModules: IModuleTuple, keepModulesOnUnmount: boolean = false) => (WrappedComponent: React.ComponentType<P>) => {
return class WithReduxDynamicModules extends React.Component<P> {
render() {
return (
<DynamicModuleLoader modules={dynamicReduxModules} keepModulesOnUnmount={keepModulesOnUnmount}>
<WrappedComponent {...this.props as P} />
</DynamicModuleLoader>
);
}
};
};
export default withReduxDynamicModule;
Thanks @ahrnee, I did not know about the with* and learned something new today. I think this is better suited as a helper function, we can provide it as a sample in our docs.
@navneet-g, sounds good. This React documentation has goes into some detail about that technique if you are looking for any more specifics. And here is an example of how it can be used:
const myWrappedComponent = withReduxDynamicModule([getModule()])(MyComponent);
Thanks @ahrnee would you mind sending a PR for documentation update?
For what it's worth, this is how I implemented my own HoF:
import React from 'react'
import { DynamicModuleLoader } from 'redux-dynamic-modules-react'
export default function withDynamicModuleLoader(Component, modules) {
const modulesArray = ( Array.isArray(modules) ) ? modules : [modules]
function Wrapper(props) {
return (
<DynamicModuleLoader modules={ modulesArray }>
<Component { ...props }/>
</DynamicModuleLoader>
)
}
const { displayName, name } = Component
Wrapper.displayName =
`withDynamicModuleLoader(${ displayName || name })`
return Wrapper
}
Which I then use thusly:
import React from 'react'
import { getModule } from './module'
export default withDynamicModuleLoader(MyComponent, getModule())
function MyComponent() {
// blah blah blah
}
Has there been any updates on this ?. Would really like this to be included with the library