redux-dynamic-modules icon indicating copy to clipboard operation
redux-dynamic-modules copied to clipboard

Suggestion for React HOC Wrapper for DynamicModuleLoader

Open jamshally opened this issue 6 years ago • 5 comments

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;

jamshally avatar May 23 '19 15:05 jamshally

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 avatar May 23 '19 16:05 navneet-g

@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);

jamshally avatar May 24 '19 02:05 jamshally

Thanks @ahrnee would you mind sending a PR for documentation update?

navneet-g avatar Jun 27 '19 19:06 navneet-g

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
}

dkreft avatar Apr 17 '20 17:04 dkreft

Has there been any updates on this ?. Would really like this to be included with the library

noelzubin avatar Sep 28 '20 10:09 noelzubin