Ad

How Can I Remove This Switch Case When The React Element Name Is Always The Same As The Switch Variable?

- 1 answer

What is a more succinct way of writing this. The pageType is always the same as the React element name and I should be able to do away with the switch statement.

import React, {Component, PropTypes} from 'react';
import Standard from './Standard/Standard';
import Banners from './Banners/Banners';

export default class ProductPages extends Component {
  static propTypes = {
    pageType: PropTypes.string.isRequired
  }

  render() {

    let ProductPage;
    switch (this.props.pageType) {
      case 'Standard':
        ProductPage = <Standard products={products}/>;
        break;
      case 'Banners':
        ProductPage = <Banners products={products}/>;
        break;
      default:
        throw new Error('pageType is not valid');
    }

    return ProductPage;
  }
}
Ad

Answer

As Standard and Banners are React components not just simple Elements you need to do something like this,

const Components = { Standard, Banners };

class ProductPages extends React.Component {
  render() {
    const ProductPage = Components[this.props.pageType];
    return <ProductPage products={ [] } />
  }
}

Example

or with React.createElement

const Components = { Standard, Banners };

class ProductPages extends React.Component {
  render() {
    return React.createElement(Components[this.props.pageType], { products: [] })
  }
}

Example

however, as you can see here the main idea to save references to Components and then use it. You can read more about this case on React GitHub issues

Note

const Components = { Standard, Banners };

is new ECMAScript 6 feature that called Object Literal Property Value Shorthand

Ad
source: stackoverflow.com
Ad