Note: This question is not a duplicate of React / JSX Dynamic Component Name. I am already aware of the solution used there in the accepted answer and if you read my question below, I am using a similar solution (using a map to convert a string to a component class) already. My question here is whether I can avoid maintaining such a map and convert the string directly to a component class.
Here is my code in index.js
:
import React from 'react'
import ReactDOM from 'react-dom'
class Foo extends React.Component {
render() {
return <h1>Foo</h1>
}
}
class Bar extends React.Component {
render() {
return <h1>Bar</h1>
}
}
function renderComponent(Component) {
ReactDOM.render(<Component />, document.getElementById('root'))
}
function getComponent(name) {
let map = {
'Foo': Foo,
'Bar': Bar,
}
return map[name]
}
renderComponent(getComponent('Foo'))
The getComponent()
function takes a React component class name as a string input and returns the corresponding class?
Currently, I have an object literal in it to map each class name to a class? Everytime I add a new class, I have to update this object literal. Is there a way I can avoid maintaining this object literal?
Is there a way to write getComponent()
in a manner that it can convert the class name as string input directly to a class?