2

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 ?

5
  • 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? Commented Dec 30, 2020 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. Commented Dec 31, 2020 at 13:52
  • I edited the question in order to be more precise about what I really want. Commented Jan 1, 2021 at 20:34
  • 1
    I believe this might lead you in the right direction: stackoverflow.com/a/65442708/1870780 Commented Jan 14, 2021 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. Commented Jan 15, 2021 at 16:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.