Mehran
Mehran

Reputation: 16821

Dynamic component names in React + Webpack + ES6

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"
  }
}

Upvotes: 2

Views: 857

Answers (1)

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>; 
}

Upvotes: 2

Related Questions