I have a page which renders different components based on user input. At the moment, I have hard coded the imports for each component as shown below:
import React, { Component } from 'react'
import Component1 from './Component1'
import Component2 from './Component2'
import Component3 from './Component3'
class Main extends Component {
render() {
var components = {
'Component1': Component1,
'Component2': Component2,
'Component3': Component3
};
var type = 'Component1'; // just an example
var MyComponent = Components[type];
return <MyComponent />
}
}
export default Main
However, I change/add components all the time. Is there a way to perhaps have a file which stores ONLY the names and paths of the components and these are then imported dynamically in another file?
You can use conditional rendering insted. Hope it will help
Check this
you could create a component building function that utilizes React.createElement. this way you can import the function from a helper file. hard to show more code in this example without more information, but you can use state helpers from this file too if your goal is to completely remove the logic from this component.
}
I think there may have been some confusion as to what I was trying to achieve. I managed to solve the issue I was having and have shown my code below which shows how I solved it.
Separate File (ComponentIndex.js):
Main File (Main.js):
This method allows me to add/remove components very quickly as the imports are in one file and only requires changing one line at a time.