1

let's consider a list of modules imported arbitrarily as so :


/**
 * modules is a list of absolute paths to modules exporting react components
 */
const getAllComponents = async(modules) => {
   const components = [];
   modules.forEach((moduleName) => {
      try {
         const module = await import(moduleName);
         components.push(module.default);
      }catch(err) {
         console.warn(err.message)
      }
   })
   return components;
}

and a parent react component in project and a random component exported from a disk based module:


// my-component.js
function MyComponent({moduleNames}) {
   const [components, setComponents] = useState([]);
   useEffect(() => getAllComponents.then(setComponents), []);
   
   // rendering a random component assuming it exists
   const RenderedComponent = components[0];
   return (
       <div>
          {/* failling here:  */}
          <RenderedComponent />
       </div>
   )
}

// a-random-component.js (disk based module whose path is in moduleNames in above component props)

function RandomComponent() {
   return (<div>propless component</div>)
}

I get the following error when compiling:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `MyComponent`.

Is there a way to render arbitrary component in the dom without having to use the static import statement ?

midugh
  • 608
  • 5
  • 21
  • What’s wrong with constructing the components based on fetched data? Are you aiming to configure elements according to a theme, serve different content based on authentication, or or create a framework? – Sam Hughes Dec 30 '20 at 23:33
  • My goal would be to be able to have arbotrary Components (extending a specific class) with their own implementations of methods. consider this as a plugin extension where the plugin exports are React Components. – midugh Dec 31 '20 at 13:52
  • I edited the question in order to be more precise about what I really want. – midugh Jan 01 '21 at 20:34
  • 1
    I believe this might lead you in the right direction: https://stackoverflow.com/a/65442708/1870780 – juliomalves Jan 14 '21 at 22:50
  • Thanks for the tip, I managed to do it on my own but I'm now running into a new problem which are using react hooks within dynamically imported components. I've been digging around a bit and it seems that it's because of copies of React within the app. Still, thanks for your comment. – midugh Jan 15 '21 at 16:21

0 Answers0