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;
}
}
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 !==
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With