Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove this switch case when the React Element name is always the same as the switch variable?

Tags:

reactjs

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;
  }
}
like image 295
SystemicPlural Avatar asked Jan 05 '16 13:01

SystemicPlural


People also ask

How do I remove an item from a React list?

To delete an item from list with React and JavaScript, we can use some array methods. to create the items state with useState . Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items. filter((_, i) => i !==

How do I remove an attribute in React?

If the removal is in a function and the key needs to be a variable, try this : removekey = (keyname) => { let newState = this. state; delete newState[keyname]; this. setState(newState) // do not wrap the newState in additional curly braces } this.


1 Answers

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

like image 103
Oleksandr T. Avatar answered Sep 23 '22 09:09

Oleksandr T.