Ad

How To Dynamically Request A React Component Based On A Variable Value?

- 1 answer

I'm wondering how to dynamically request a component based on a variable value. What I'm trying to accomplish here is the following:

import Template1 from './Template1.jsx';
import Template2 from './Template2.jsx';

var ComponentTemplate = (some_condition === true) ? "Template1" : "Template2"

render() {
    <ComponentTemplate prop1="prop1 val" />
}

Is this even possible? If so, how?

Ad

Answer

It is not clear to me why you need to use a string representation of a class rather than just switch the component or use a conditional render:

var Component = some_condition === true ? Template1 : Template2;
// ...
return ( <Component /> );

But assuming this is an oversimplification, the easiest thing to do would be to use a mapping object that translates a string into a component. With ES2015 enhanced object literals, it becomes fairly straightforward:

var Components = {
  Template1,
  Template2,
};

var Component = condition ? Components['Template1'] : Components['Template2'];

// ...

return ( <Component /> );
Ad
source: stackoverflow.com
Ad