5

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;
  }
}
3
  • As Standard and Banners are React components not just simple Elements you need do something like this jsfiddle.net/69z2wepo/26495 Commented Jan 5, 2016 at 14:41
  • 1
    or with React.createElement - jsfiddle.net/69z2wepo/26496 Commented Jan 5, 2016 at 14:42
  • 1
    Nice solution! Post an answer for an upvote :) Commented Jan 5, 2016 at 14:44

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

When will one work and other wouldn't ? I am facing an issue where using <ProductPage/> doesn't work, but using {React.createElement(ProductPage)} works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.