How can I remove this switch case when the React Element name always matches the switch variable?

Which is a shorter way of writing this. The page type always matches the name of the React element, and I should be able to get rid of 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; } } 
+5
source share
1 answer

Since Standard and Banners are components of React 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, since you can see the main idea here, to save references to Components and then use it. You can learn more about this case at Respond to GitHub Issues

Note

 const Components = { Standard, Banners }; 

- a new ECMAScript 6 feature called Literal Object Cost Reduction

+6
source

Source: https://habr.com/ru/post/1239893/


All Articles