Majki Majki -4 years ago 96
React JSX Question

React - JSX returned by a function doesn't get converted into a Component

I'm trying to dynamically pull Components based on ID however even though my function returns the correct JSX it wouldn't get converted into a Component in my render method.

renderModule(moduleId) {
let AddModule = "Modules.module" + moduleId
let returnModule = <AddModule/>
// console.log(returnModule)
return returnModule
}

render() {
return (
<div>
<ul>
{this.props.templateModules.map((module, index) =>
<TemplateContent
removeModule={this.removeModule}
key={index}
>
{this.renderModule(module)}
</TemplateContent>
)}
</ul>
</div>
)
}


My TemplateContent code:

const TemplateContent = (props) => {

return (
<div>
{props.children}
</div>
)

}


So in the browser I can see instead of the object. However if I assign to returnModule it does render correctly.

Even though I can see the object in the console when it's created from variable AddModule it still wouldn't get passed on in the render method.

What am I doing wrong? I'm importing my modules in index.js file from modules folder.

import * as Modules from '../components/modules'

Thanks a lot in advance! :)

Answer Source

Your code is currently passing a string like 'Modules.module1' to React.createElement, not a reference to the module Module.module1 itself. You need to convert the module name to a reference on the Modules import:

import * as Modules from '../components/modules'

// ...

renderModule(moduleId) {
    // Will be a reference to the component, not a string
    let AddModule = Modules[`module${moduleId}`]
    let returnModule = <AddModule/>
    return returnModule
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download