2

I've defined two React components like this:

class CmpA extends React.Component
{ ... }

class CmpB extends React.Component
{ ... }

As you can see they are defined in ES6 syntax. And I use Webpack and Babel to trans-compile them to ES5. What I want to do is to store a component definition in a variable and then render it:

render() {
    let Cmp = Math.random() > 0.5 ? CmpA : CmpB;
    return <Cmp />;
}

But it does not work since the above code translates to:

render() {
    var Cmp = Math.random() > 0.5 ? CmpA : CmpB;
    return _react2.default.createElement('Cmp', {});
}

Does anyone know how to overcome this problem?

[UPDATE]

Please also consider that I would need to use Cmp like this:

render() {
    let Cmp = Math.random() > 0.5 ? CmpA : CmpB;
    return <div><Cmp /></div>;
}

Or in other words, I need to be able to name a component dynamically!

[UPDATE]

Here's my project's package.json file's content:

{
  "name": "expandable-react-redux",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Mehran",
  "license": "ISC",
  "dependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "react": "^15.0.1",
    "react-dom": "^15.0.1",
    "react-redux": "^4.4.2",
    "redux": "^3.4.0"
  },
  "devDependencies": {
    "babel-core": "^6.7.6",
    "babel-loader": "^6.2.4",
    "react-hot-loader": "^1.3.0",
    "webpack": "^1.12.14"
  }
}
3
  • I don't get the 'Cmp' when I try it. Are you sure? babeljs.io/repl/… Commented Apr 29, 2016 at 22:58
  • The code is pasted here so yeah, I'm pretty sure. Maybe it's because of the dependencies that I've used in my package.json! I'll include that in my question. Commented Apr 29, 2016 at 23:11
  • 1
    It must be something wrong with a bundling process. It may be helpfull to look at your .babelrc and webpack.config.js. Commented Apr 30, 2016 at 10:27

1 Answer 1

2

I believe You could do it this way:

render() {
    const props = { prop1: 10 };
    let Cmp = Math.random() > 0.5 ? <CmpA {...props} /> : <CmpB {...props} />;
    return <div>{Cmp}</div>; 
}
Sign up to request clarification or add additional context in comments.

4 Comments

You're answer is correct but not something I'm looking for! I've updated my question to better reflect my problem.
Updated the answer to match your question.
Thanks, but can I also somehow set properties for the {Cmp}? Like {Cmp prop1="10"}?
You can proxy the props with spread operator: <CmpA {...props} />.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.