How to handle circular dependency on nested components? (using es6 classes)

I am using React with Babel (es6). I have a problem to solve circular dependency between my components.

I create a menu in which we have:

  • ItemFactory
  • Itemfolder
  • ItemGeneric
  • MoreTypesOfItems

ItemFactory just returns any of the other components based on the details passed.

ItemFoldermust be able to reuse ItemFactoryto create nested menu items.

Component ItemFactory, itemFactory.js (simplified):


// I need ItemFolder
import ItemFolder from './itemFolder'

// import all different items too

...

function ItemFactory (props) {
  switch (props.type) {
    case 'link': return <ItemLink {...props} />
    case 'blank': return <ItemBlank {...props} />
    case 'folder': return <ItemFolder {...props} />
    default: return <ItemGeneric {...props} />
  }
}

modules.exports = ItemFactory

ItemFolder Component, itemFolder.js (simplified):


// I need the itemFactory
import ItemFactory from './itemFactory'
...
Items = props.items.map(item => {
  return <ItemFactory {...item} />
})

module.exports = ItemFolder

As you can see, both require each other. This causes some circular dependency problem when I get an empty object.

Any help is appreciated :)

+4
2

, . , (, ).

, CommonJs. :

// itemFactory.js
import ItemFolder from './itemFolder'
…

export default function ItemFactory(props) {
  switch (props.type) {
    case 'link': return <ItemLink {...props} />
    case 'blank': return <ItemBlank {...props} />
    case 'folder': return <ItemFolder {...props} />
    default: return <ItemGeneric {...props} />
  }
}

// itemFolder.js
import ItemFactory from './itemFactory'
…

export default function ItemFolder(props) {
  let items = props.items.map(item => {
    return <ItemFactory {...item} />
  })
  …
}
+4

ItemFactory. , factory :

const components = {};

export function registerComponent(name, Component) {
    components[name] = Component;
};

export default function ItemFactory(props) {
    const C = components[props.type];
    return <C {...props} />;
}


// ItemFolder.js
import {registerComponent}, ItemFactory from 'itemFactory';

export default class ItemFolder {
    ...
};

registerComponent("folder", ItemFolder);
+1

Source: https://habr.com/ru/post/1629925/