0

I have strings as parameter in a function and it would return a component of the same naming, example

myFunc('Home') or myFunc('MyComponent')

which should return

<Home /> or <MyComponent />

I know that I can do this

var mappings = {
  Home: <Home />,
  MyComponent: <MyComponent />
};

return mappings['Home'];  // returns <Home />

or

return mappings['MyComponent']  // returns <MyComponent />

But can I just go straight to return the component with the same name as the parameter without creating the object mappings above?

The Reason
  • 7,705
  • 4
  • 24
  • 42
Alexander
  • 1,729
  • 3
  • 19
  • 36
  • There's a React 16 answer here: https://stackoverflow.com/questions/43800784/get-component-name-in-react - looks like it doesn't work if you minify though (as you would for production). I think it's probably safer to have a mapping. Little more verbose, but time spent trying to streamline something like this is usually more effort than it saves, and making an explicit mapping can prevent weird, hard to trace errors (like the aforementioned failure when you uglify or minify your code). – Jayce444 Apr 26 '18 at 09:10

1 Answers1

0

There is no way that you can do something like this:

function myFunc(componentName) {
    return < <componentName> />;
}

Although this is not bad observation, this is just digging down to minimize code as much and for not much benefit, only to find out if language can do that.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62