ReactJS: How can I have a more modular use of prop types & shapes for objects?

dmonopoly picture dmonopoly · Apr 28, 2015 · Viewed 9.6k times · Source

I like to explicitly specify all my prop types for every class.

React.createClass({
  propTypes: {
    optionalArray: React.PropTypes.array,
    optionalBool: React.PropTypes.bool,
...

This is from reading reusable components: https://facebook.github.io/react/docs/reusable-components.html

However, what if I have a very common object that I use in many classes? For example:

var MemoryForm = React.createClass({
  propTypes: {
    memory: React.PropTypes.shape({
      memoryID: React.PropTypes.number,
      content: React.PropTypes.string,
      date: React.PropTypes.object,
      dateStr: React.PropTypes.string,
      note: React.PropTypes.string
    }).isRequired,
    ...

var MemoriesArea = React.createClass({
  propTypes: {
    // The initial memory to fill the memory form with.
    formMemory: React.PropTypes.shape({ // <== shape used again
      memoryID: React.PropTypes.number,
      content: React.PropTypes.string,
      date: React.PropTypes.object,
      dateStr: React.PropTypes.string,
      note: React.PropTypes.string
    }).isRequired,
    // ...



var Playground = React.createClass({
  getInitialState: function() {
    var initVars = {
      // The initial memory to fill the memory form with.
      formMemory: {  // <== shape is used again.
        memoryID: 0,
        content: "",
        date: null,
        dateStr: "",
        note: ""
      }
    };
    return initVars;
  }
  //...

Here, I use the 'memory' shape very frequently in the prop types for various classes, as well as in some initializations. How can make this more DRY - i.e., less code duplication, so a change to this object shape will be more maintainable in the future?

Answer

Andreas Profous picture Andreas Profous · Jun 9, 2016

I had the same problem and just moved the values to a separate ES6 module. In your example:

// File lib/PropTypeValues.js
import { PropTypes } from 'react';

export let MemoryPropTypes = PropTypes.shape({
  memoryID: PropTypes.number,
  content: PropTypes.string,
  date: PropTypes.object,
  dateStr: PropTypes.string,
  note: PropTypes.string
}).isRequired

Then in your client code:

// MemoryForm.jsx
import { MemoryPropTypes } from './lib/PropTypeValues'
import React from 'react';

class MemoryForm extends React.Component {
  static propTypes: {
    memory: MemoryPropTypes,
    // ...
  };
}

Hope this helps.