1

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?

Lone Learner
  • 18,088
  • 20
  • 102
  • 200
  • 1
    Possible duplicate of [React / JSX Dynamic Component Name](https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name) – skyboyer Apr 21 '19 at 05:02
  • Are you importing components from other files? – Pouya Jabbarisani Apr 21 '19 at 05:18
  • @PouyaJabbarisani No, I am not importing components from other files. You can see my source code in the question. – Lone Learner Apr 21 '19 at 05:38
  • @skyboyer I am confused how the link you have mentioned answers my question. The answer there uses a `Components` map to look up the component class for a given string. Isn't that exactly what I am already doing here with the `map` object literal in my question? – Lone Learner Apr 21 '19 at 05:45
  • 1
    *My question here is whether I can avoid maintaining such a map and convert the string directly to a component class.* - no, otherwise it would be suggested in dupe question. It is still a dupe. – Estus Flask Apr 21 '19 at 06:00
  • fair enough, I should add something as a description. For just-a-gloabl-function you could get it through `window[dynamicFunctionName]` but for class it does not work. So there is no workaround. Keep using explicit mapping or refactor your app so you would not need instantiate component by name. – skyboyer Apr 21 '19 at 06:56

0 Answers0