Code tips #5: React – How to avoid extra control property

In React many times we have components that have some slight variations and we want to control how these components will be rendered. For example, we have a mobile and a desktop version of a component. Usually React developers tend to add an extra property in the component based on which they control the version of the component that will be rendered, either through if or switch statements.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ProductCardSmall from './ProductCardLarge';
import ProductCardMedium from './ProductCardMedium';
import ProductCardLarge from './IPBadgeLarge';

export default class ProductCard extends Component {
  static propTypes = {
    cardType: PropTypes.string,
  };

  render() {
    const { cardType } = this.props;

    switch (cardType) {
      default:
      case 'small':
        return <ProductCardSmall {...this.props} />;
      case 'medium':
        return <ProductCardMedium {...this.props} />;
      case 'large':
        return <ProductCardLarge {...this.props} />;
    }
  }
}

And then use the component like:

<ProductCard cardType="medium" />

But there is a way to simplify the code by

using static and avoid having this extra control property.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ProductCardSmall from './ProductCardLarge';
import ProductCardMedium from './ProductCardMedium';
import ProductCardLarge from './IPBadgeLarge';

export default class ProductCard extends Component {
  static Small = props => <ProductCardSmall {...props} />;
  static Medium = props => <ProductCardMedium {...props} />;
  static Large = props => <ProductCardLarge {...props} />;

  render() {
    return <ProductCard.Small {...this.props} />
  }
}

And then use the component like:

<ProductCard.Medium />

Leave a Reply

Your email address will not be published. Required fields are marked *